Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions isort/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,18 @@ def _with_from_imports(
comment = (
parsed.categorized_comments["nested"].get(module, {}).pop(from_import, None)
)
if (
comment is not None
and from_import in as_imports
and config.multi_line_output != wrap_modes.WrapModes.NOQA
):
# This name also has an alias; the leading-alias loop keeps the two
# together on a later pass. Popping the comment here would drop the
# alias, so put it back and leave the name for that loop.
parsed.categorized_comments["nested"].setdefault(module, {})[
from_import
] = comment
continue
if comment is not None:
# If the comment is a noqa and hanging indent wrapping is used,
# keep the name in the main list and hoist the comment to the statement.
Expand Down
20 changes: 20 additions & 0 deletions tests/unit/test_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2386,3 +2386,23 @@ def test_isort_skip_is_honored_with_future_import_issue_2092():
skip_index = next(i for i, line in enumerate(lines) if "# isort: skip" in line)
assert lines.index("import ccc") > skip_index # skip not relocated below the block
assert isort.code(sorted_interleaved) == sorted_interleaved


def test_isort_does_not_drop_aliased_import_when_plain_name_has_a_comment():
"""A name imported both plainly (with a trailing comment) and aliased must keep its
alias when a sibling sorts ahead of it.

``from x import m # c`` and ``from x import m as z`` combine into one group, and the
alias is only emitted while ``m`` leads that group. When ``aaa`` sorts before ``m`` the
comment pass used to consume ``m`` and drop ``m as z``, which only surfaced on a second
run once the group was re-sorted.
"""
to_sort = "from x import aaa\nfrom x import m # c\nfrom x import m as z\n"
assert isort.code(to_sort) == to_sort

# The same holds for a relative (local-folder) import.
relative = "from . import bar, one\nfrom . import one as zzz # NOQA\n"
relative_sorted = isort.code(relative)
expected = "from . import bar\nfrom . import one # NOQA\nfrom . import one as zzz\n"
assert relative_sorted == expected
assert isort.code(relative_sorted) == relative_sorted
Comment on lines +2404 to +2408

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you write out the expected code here instead of using "..." in