PyCQA / isort

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

Comments moving bug when using import aliases #1839

Open JMMarchant opened 2 years ago

JMMarchant commented 2 years ago

I'm seeing a bug(?) where if a from import has an alias, is too long for a single line, and has a comment after the import (for instance a mypy comment) then the comment is getting incorrectly sorted onto the wrong line. See the example below:

Input: test.py

from a_long_name_to_enforce.splitting_across.two_lines import (  # type: ignore[attr-defined]
    a_random_attribute as renamed_random_attribute,
)

Expected No change; comment stays on line as this is the actual line that mypy complains about.

Observed

from a_long_name_to_enforce.splitting_across.two_lines import (
    a_random_attribute as renamed_random_attribute,  # type: ignore[attr-defined]
)

Comment is shifted down onto the alias line instead.

webknjaz commented 2 years ago

I was just about to report exactly the same bug, except in my case it's flake8's # noqa comments that get moved on a different line making it impossible to apply the ignores to the lines that actually introduce the linting violations. Also, I use multi_line_output = 5.

webknjaz commented 2 years ago

Oh, wait. I was using v5.4.2 and upgrading to v5.10.1 fixed my problem.

alberto commented 2 years ago

I'm using isort 5.10.1 and still have this issue.

qi55wyqu commented 9 months ago

I noticed that isort does not produce the same output each time.

When I add these imports

from typing import (
    IO,
    Any,
    ContextManager,
    Final,
    Optional,
    cast as typingCast  # avoid naming collision
)

and run isort, it changes to

from typing import IO, Any, ContextManager, Final, Optional
from typing import cast as typingCast  # avoid naming collision

If I run it again, it changes to

from typing import (  # avoid naming collision
    IO,
    Any,
    ContextManager,
    Final,
    Optional,
    cast as typingCast
)

I'm using isort 5.13.2 with these settings

py_version=310
line_length=100
multi_line_output=3
combine_as_imports=true