PyCQA / isort

A Python utility / library to sort imports.
https://pycqa.github.io/isort/
MIT License
6.49k stars 580 forks source link

Found a dangerous edge case: Comment converted to code #1949

Open phil20686 opened 2 years ago

phil20686 commented 2 years ago

running isort over the following file:

from math import sqrt

if __name__ == "__main__":
    thing = sqrt(3)
#   some random comments
    from datetime import datetime
    dt = datetime(2020,1,1)

Leads to the comment being converted to code

from math import sqrt

if __name__ == "__main__":
    thing = sqrt(3)
some random comments
    from datetime import datetime
    dt = datetime(2020,1,1)

will be the output. The isort version is 5.10.1. I have not checked all isort versions.

mawillcockson commented 2 years ago

I minimized the original example a bit:

import sys

if True:
#   comment
    import sys

I used this script with git bisect, which pointed to 67b2a54fdb314650f477d7a8aa9aa46e0245d6e5, which is now:

https://github.com/PyCQA/isort/blob/12cc5fbd67eebf92eb2213b03c07b138ae1fb448/isort/core.py#L415-L418

anirudnits commented 1 year ago

This is similar to #2087.

anirudnits commented 1 year ago

I'm trying to come up with a solution for this, I added comments on why this is happening and the difficulties I'm facing while resolving them.