PyCQA / isort

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

isort copies comments across imports #2282

Open nicolasstucki opened 1 month ago

nicolasstucki commented 1 month ago

Given this file,

from foo import a, b  # comment
from foo import c as d
from foo import e

the result of isort is

from foo import a, b  # comment
from foo import c as d
from foo import e  # comment
nicolasstucki commented 1 month ago

This is particularly problematic with # pyright: ignore comments as it starts duplicating them. In general, this might break any tool that uses comments semantically in import lines.

Helveg commented 1 month ago

You could use a temporary workaround by enabling the combine_as_imports configuration and would give you this output:

from foo import a, b, c as d, e  # comment

if that works for you?

Helveg commented 1 month ago

The problem seems to be that isort categorizes the from foo import a, b # comment as a from-type comment belonging to the entire foo module, and then considers it a comment for all from foo import statements (as-imports are treated differently). The solution is to have the comment categorized as a nested-type comment for the foo.a and foo.b members. isort does this properly for the 4th statement in this snippet:

from foo import a, b
from foo import c as d
from foo import e
from foo import f # comment-f

whose output shows that for nested comments there's no duplication:

from foo import f # comment-f
from foo import a, b
from foo import c as d
from foo import e
nicolasstucki commented 1 month ago

I used this workaround

from foo import a # comment
from foo import b # comment
from foo import c as d
from foo import e