Skip to content

Keep the comment of a wrapped X as X import - #2742

Open
Enesuygurs wants to merge 2 commits into
PyCQA:mainfrom
Enesuygurs:issue/2741
Open

Enesuygurs wants to merge 2 commits into
PyCQA:mainfrom
Enesuygurs:issue/2741

Conversation

@Enesuygurs

Copy link
Copy Markdown

Fixes #2741

When an X as X import with a trailing comment is wrapped with backslashes, the comment on the continuation line X # comment is stored in nested_comments under "X". After alias handling the original name X is still in just_imports, so the plain-name loop in parse.file_contents gives the comment to a plain X. That name isn't imported directly, so the comment is never written.

isort itself wraps a long X as X import with a comment this way under the default grid mode. So a second run removes the comment, and isort --check fails on isort's own output:

from mypackage.config import ConfigurationManager as ConfigurationManager  # pylint: disable=useless-import-alias

The first run gives

from mypackage.config import \
    ConfigurationManager as \
    ConfigurationManager  # pylint: disable=useless-import-alias

and the second run gives from mypackage.config import ConfigurationManager as ConfigurationManager, without the comment.

This change skips names that are only imported under an alias in that loop, so the comment stays with the aliased import. With remove_redundant_aliases the import becomes a plain X, so the existing behaviour is kept there.

I added a regression test to tests/unit/test_regressions.py. It covers the wrapped case, idempotence, the \ and parenthesized short forms, and remove_redundant_aliases. It fails before the change and passes after it. The unit tests, ruff, flake8 and the isort self-check pass.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Statements containing multiple aliases can attach a preserved directive to the wrong import.

1 open issue
What changed in this PR

This PR addresses #2741 by preserving trailing comments on wrapped X as X imports, preventing comment loss on subsequent isort runs.

Changes:

  • Adjusts parser comment handling for names imported only under aliases.
  • Adds regression coverage for wrapped imports, idempotence, short forms, and redundant-alias removal.
File Description
tests/​unit/​test_regressions.py Adds comment-preservation and idempotence regression tests.
isort/​parse.py Skips plain-name comment assignment for alias-only imports.

Review effort: Balanced

Comment thread isort/parse.py Resolved
@codecov

codecov Bot commented Oct 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.38%. Comparing base (a514c71) to head (c255c10).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2742   +/-   ##
=======================================
  Coverage   99.38%   99.38%           
=======================================
  Files          40       40           
  Lines        3274     3276    +2     
  Branches      706      707    +1     
=======================================
+ Hits         3254     3256    +2     
  Misses         12       12           
  Partials        8        8           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@DanielNoord DanielNoord left a comment

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.

Please have a look at the AI review.

@Enesuygurs

Copy link
Copy Markdown
Author

Good catch from the review, thanks. The comment on a wrapped b as b is now stored under the b as b key, so it stays on the alias it was written on instead of moving to the first one, and I added tests for the multiple-alias cases and their idempotence.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The new bare-name mapping may collide with existing alias comments when imports share an alias, and runtime validation remains outstanding because isolated verification could not access the source snapshot.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

Comment thread isort/parse.py
associated_comment = nested_comments.get(import_name)
if associated_comment is not None:
categorized_comments["nested"].setdefault(import_from, {})[import_name] = (
categorized_comments["nested"].setdefault(import_from, {})[comment_key] = (

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

With combine_as_imports=True, I hit a case where the formatter keeps the text of a type-checker directive but stops it from working:

from pathlib import (  # type: ignore[attr-defined]
    Path as
    Path,  # public re-export
    project_path as exported_path,
)

The formatted opening line becomes from pathlib import ( # public re-export; type: ignore[attr-defined]. Python's ast.parse(..., type_comments=True) then finds no ignore directive. I also checked with mypy 2.4.1: the input and base-format output pass, while the formatted output from this branch reports [attr-defined].

Could the combined form keep the directive first on its line, or keep the comments on separate import lines for this case?

@Enesuygurs

Copy link
Copy Markdown
Author

Thanks for checking this. The ordering itself isn't new with this PR: on main, the same input with the alias on one line (Path as Path, # public re-export) already comes out as from pathlib import ( # public re-export; type: ignore[attr-defined], because with combine_as_imports the opening-line comments are appended after the nested ones in output.py. Before this PR the wrapped form just lost the # public re-export comment, which is why the directive happened to stay first; this change makes it behave like the one-line form. I'd rather keep this PR focused on the dropped comment and fix the ordering in a separate issue/PR, unless the maintainers prefer it here.

@DanielNoord
DanielNoord self-requested a review December 2, 2026 20:33
@DanielNoord

Copy link
Copy Markdown
Member

Please rebase this on main :)

When an import aliased to its own name was split over several lines, the
comment on the last line was stored under the bare name and then handed to
the plain import of that name, which is not imported directly. The comment
was not written out at all. isort wraps a long `X as X` import with a comment
like that itself, so the second run removed the comment, and `--check` failed
on isort's own output.

Only use a comment found under a bare name for names that are imported
directly.

Fixes PyCQA#2741
With several `X as X` imports in one statement, the comment on a
continuation line holding just an alias was attached to the first alias of
the statement: `from pkg import (a as a, b as\n    b)  # type: ignore`
moved the comment to `a as a`. Store it under the matching `X as X` key
instead, so it stays on the import it was written on.
@Enesuygurs

Copy link
Copy Markdown
Author

Rebased on main.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Comment of a wrapped X as X import is removed on the next run (not idempotent)

4 participants