Repository navigation
Conversation
When names whose comments cannot share a statement were split over several statements, each of those statements could group more names and carry a comment on its opening line. On the next run isort reads all of those comments as belonging to the first statement for the module, so it regrouped the names, `--check` rejected isort's own output, and comments such as `# type: ignore[...]` or `# noqa: F401` ended up on other names. Group the names without a comment into the first statement, and give every later statement a single commented name whose comment stays on that line.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #2781 +/- ##
==========================================
- Coverage 99.39% 99.16% -0.23%
==========================================
Files 40 40
Lines 3279 3359 +80
Branches 707 728 +21
==========================================
+ Hits 3259 3331 +72
- Misses 12 14 +2
- Partials 8 14 +6 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🟡 Changes recommended
Import regrouping can reverse colliding alias bindings and change runtime behavior, while unresolved comment-handling defects break two-pass stability and E501 suppression.
4 open issues
What changed in this PR
This PR addresses repeat-run instability in grouped from imports, aiming to preserve comment attachment and make freshly sorted files pass isort --check.
Changes:
- Collect uncommented names into the first statement while skipping conflicting comments.
- Keep later commented names separate and account for combined-alias comments and
noqaplacement. - Add two-pass regression coverage for default settings, the black profile, and
combine_as_imports.
| File | Description |
|---|---|
tests/unit/test_regressions.py |
Adds regression cases for stable grouping across consecutive sorts. |
isort/output.py |
Adjusts import grouping, comment classification, and later-statement formatting. |
Review effort: Max
Keep deferred imports and aliases in the intended order, retain stable comment classification after joining, and preserve NOQA wrapping and section-sort stability. Add regressions for the review cases in PyCQA#2781. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved import-ordering and comment-handling defects can change runtime alias bindings and disable type-checker suppressions.
6 open issues
Preserve order only for comment-sensitive import groups · New Bypass formatting only for preserved noqa comments · New Prevent deferral from moving imports across queued aliases · New Keep preserve_order decisions stable across formatting runs · New Keep combined aliases stable across formatting runs · New Stop rescanning suffixes for individually commented imports · New
4 resolved since last review
Review effort: Max
| and len(imports) == 1 | ||
| and not has_noqa_comment | ||
| and not preserve_comments_on_statement_line | ||
| and config.multi_line_output != wrap_modes.WrapModes.NOQA |
| or (grouped_has_explanation and bool(pragma_comments)) | ||
| ) | ||
| if incompatible: | ||
| if preserve_order or any( |
|
I ran the six Copilot points against 062f80d, the first commit 3936b83, and main (eb62da3), with Python 3.13 in a container. Script below.
So 1, 2, 4 and 6 come from 062f80d, and 3 and 5 from my first commit. I can work on 3 and 5; I have not pushed anything since your commit, to avoid clashing with your changes. Scriptimport sys, time, types
import isort
from isort.wrap_modes import WrapModes
x = types.ModuleType("x")
for n in ["a", "b", "c", "getX", "get_x"] + [f"n{i}" for i in range(2000)]:
setattr(x, n, f"x.{n}")
sys.modules["x"] = x
def bind(src, names):
ns = {}
exec(src, ns)
return {n: ns.get(n) for n in names}
CASES = [
("3c control: shadowing alias, no comments", "from x import a as c\nfrom x import c\n", {}, ["c"]),
("3d control: plain then alias, no comments", "from x import c\nfrom x import a as c\n", {}, ["c"]),
("1c control: open_stack, no comments", "from x import getX as bb\nfrom x import get_x as bb\n", dict(profile="open_stack"), ["bb"]),
("1 open_stack alias order", "from x import getX as bb\nfrom x import get_x as bb # pylint: disable=x\n", dict(profile="open_stack"), ["bb"]),
("3 deferred alias", "from x import a # explanation\nfrom x import a as c\nfrom x import b # type: ignore\nfrom x import c\n", {}, ["a", "b", "c"]),
("5 combine_as parenthesized", "from x import ( # explanation\n a as aa,\n b as bb, # noqa: F401\n)\n", dict(combine_as_imports=True), ["aa", "bb"]),
("4a ignore_comments+no_inline_sort", "from x import a # one\nfrom x import b as bb\nfrom x import c # two\nfrom x import a as aa\n", dict(ignore_comments=True, no_inline_sort=True), ["a", "bb", "c", "aa"]),
("4b only_sections", "from x import c as cc # one\nfrom x import b\nfrom x import a as aa # two\nfrom x import c\n", dict(only_sections=True), ["cc", "b", "aa", "c"]),
("2 NOQA long type-ignore", "from x import getX # type: ignore[attr-defined]\n", dict(multi_line_output=WrapModes.NOQA, line_length=30), ["getX"]),
]
for title, src, cfg, names in CASES:
out1 = isort.code(src, **cfg)
out2 = isort.code(out1, **cfg)
try:
same = bind(src, names) == bind(out1, names)
except Exception as e:
same = f"exec error {e!r}"
print(f"--- {title}\n{out1}idempotent={out1 == out2} bindings_same={same}")
if out1 != out2:
print(f"second run:\n{out2}")
print("--- 6 timing: n `# type: ignore` single-name imports")
for n in (100, 200, 400):
src = "".join(f"from x import n{i} # type: ignore\n" for i in range(n))
t = time.perf_counter(); isort.code(src); dt = time.perf_counter() - t
print(f"n={n} {dt:.3f}s") |
|
Thanks @PDGGK I just used my own agent to work on the initial review from Copilot as I'd like to resolve this before releasing Now that you are here again perhaps you have a better idea how to resolve all review comments without ballooning the size of this PR? |
…nt-grouping-idempotent
When the comments on the names of a `from` import could not share one statement, the names were split over several statements, and a later statement could group more names under a comment on its opening line. The next run attaches such a comment to the first statement for the module, so the names were regrouped, `--check` rejected isort's own output, and comments such as `# noqa: F401` or `# type: ignore[...]` moved onto other names. A later statement for a module now holds either a single commented name, kept on one line, or names without comments. The first statement may skip a name whose pragma comment it cannot share, so that the names without comments still go into it, but only when the module has no aliases and its names are sorted, so that no name moves past an alias or out of the order in which it was written.
|
Here is a smaller version, redone on top of current It keeps the approach of my first commit, with these changes:
With this, points 1, 2, 4 and 5 give the same output as So that nothing of yours is lost, I pushed it on top of 062f80d as a revert of both earlier commits, a merge of |
| and not has_noqa_comment | ||
| # A later statement keeps a `noqa` comment on its name too, see | ||
| # `_with_from_imports_for_module`. | ||
| and not (has_noqa_comment and first_statement) |


With 10.0.0b2 and on
main, isort can change its own output on the next run when thefromimports of a module carry comments that cannot share one statement.isort --checkthen fails on a file isort has just sorted, and the second run moves the comments onto other names. 9.0.2 is not affected; this comes from the grouping added in #2614.When the grouping loop reaches a name whose comment cannot join the current statement, it stops there. Here that is a
# noqaafter an explanatory comment, and a second# type: ignoredoes the same. The next statement then groups the following names as well, so several statements for the module carry a comment on their opening line. When isort reads the output back, it attaches all of those comments to the first statement of the module, because only a single name on one line keeps its own comment. So the names get regrouped.This change makes the output read back the same way:
no_inline_sortoronly_sections), so no name moves past an alias or out of the order in which it was written; otherwise it stops there, as onmain. After skipping a name it stops at the next explanatory comment.With this branch:
All three commands exit 0.
I found this by running 10.0.0b2 twice over about 8,000 files of real code: 25 projects plus the packages installed in isort's dev environment. With default settings, truststore's
_windows.pychanged on the second run (# type: ignore[attr-defined]moved ontoPOINTER, Structure), and with the black profile pendulum'shelpers.pychanged as well.Testing
tests/unit/test_regressions.py: one sorts each input twice and checks that the second run changes nothing and that every name still refers to the same object; the other checks the exact output for the example above and for a later commented import in NOQA wrap mode. 9 of the 14 cases fail onmain; the other five cover the Copilot review points, whichmainalready handles.mypy,ruff check,ruff format --check,flake8andbanditare clean.main6 and 7 files change on the second run, with this branch none do.mainto 5,734 (of 42,000 runs).Known limits:
no_inline_sortoronly_sections, does not get the compact grouping: names without comments after a conflicting comment go into a statement of their own.combine_as_imports, such as(a as aa, # noqa/b, # explanation/c,), still changes on the second run, as onmain.no_inline_sort,only_sectionsorforce_sort_within_sectionswithlength_sortcan order them differently thanmaindoes.maindoes not keep their input order there either; the random test above changed what a name refers to in 8,509 runs onmainand 8,496 with this branch.