diff --git a/isort/output.py b/isort/output.py index 7fa6e3e6f..7ca69ed2f 100644 --- a/isort/output.py +++ b/isort/output.py @@ -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. diff --git a/tests/unit/test_regressions.py b/tests/unit/test_regressions.py index da00a5dd3..090433525 100644 --- a/tests/unit/test_regressions.py +++ b/tests/unit/test_regressions.py @@ -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