PyCQA / isort

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

Unindented comments get malformed #1899

Open mattmess1221 opened 2 years ago

mattmess1221 commented 2 years ago

isort version: 5.10.1

Unindented comments in an indented block seem to get cut off at the indent, which generates a syntax error.

Code:

import sys

if True:
# this will get cut off
    import os

Output:

import sys

if True:
is will get cut off
    import os
anirudnits commented 2 years ago

Hello @killjoy1221, thanks for raising this! I can verify that this a bug and apparently happens with all the default settings. I'll investigate the root cause for this and try to resolve it. Thanks again for flagging this

anirudnits commented 2 years ago

I have created a PR and for the time being added a failing test to keep this issue active and am working to resolve this

anirudnits commented 2 years ago

I identified the root cause of the problem: https://github.com/PyCQA/isort/blob/c6a41965247a858a0afd848fbebfca18b8983917/isort/core.py#L411-L414

The line[len(indent): ] portion is causing the initial part of the un-indented comment to be cut off. The simple solution is change the above section to line.strip() or equivalent, however with that some other tests are failing. I'm looking into this and debugging the failed tests as well to understand the cause there.