PyCQA / isort

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

isort uncomments code when odd indentation is next to an import #2087

Open pfranz opened 1 year ago

pfranz commented 1 year ago

I came across a bug where isort strips off the leading characters (in my case a comment) when there's indentation next to an import. I found this in an older version of isort, but still see it in 5.12.0

#!/usr/bin/env python3

if True:
# this comment breaks
    import sys

when invoked with isort break_isort.py results in

#!/usr/bin/env python3

if True:
is comment breaks
    import sys
anirudnits commented 1 year ago

The value for the indentation level of the comment gets set here: https://github.com/PyCQA/isort/blob/main/isort/core.py#L340, basically whats this is doing is setting the indentation level of the whole block without imports to the new indentation of the import block.

anirudnits commented 1 year ago

I'm thinking of the various use-cases that arise there, one simple fix here is to the convert the last conditional in line#338 to

...
and ( not did_contain_imports and len(new_indent) < len(indent) )

that would solve this issue but this my interfere with certain cimports.