Skip to content

Keep the grouping of commented from imports stable across runs - #2781

Open
PDGGK wants to merge 5 commits into
PyCQA:mainfrom
PDGGK:fix-from-import-comment-grouping-idempotent
Open

PDGGK wants to merge 5 commits into
PyCQA:mainfrom
PDGGK:fix-from-import-comment-grouping-idempotent

Conversation

@PDGGK

@PDGGK PDGGK commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

With 10.0.0b2 and on main, isort can change its own output on the next run when the from imports of a module carry comments that cannot share one statement. isort --check then 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.

$ cat example.py
from os.path import basename  # used below
from os.path import dirname
from os.path import exists  # noqa: F401
from os.path import join

print(basename, dirname, join)
$ isort - < example.py > sorted.py; cat sorted.py
from os.path import basename, dirname  # used below
from os.path import exists, join  # noqa: F401

print(basename, dirname, join)
$ isort --check - < sorted.py
ERROR:  Imports are incorrectly sorted and/or formatted.
$ isort - < sorted.py > sorted2.py; cat sorted2.py
from os.path import basename, dirname, exists, join  # used below; noqa: F401

print(basename, dirname, join)
$ flake8 --select F401 sorted.py sorted2.py
sorted2.py:1:1: F401 'os.path.exists' imported but unused

When the grouping loop reaches a name whose comment cannot join the current statement, it stops there. Here that is a # noqa after an explanatory comment, and a second # type: ignore does 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:

  • Only the first statement for a module may group names under a comment. A later statement 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. It does so only when the module has no aliases and its names are sorted (no no_inline_sort or only_sections), so no name moves past an alias or out of the order in which it was written; otherwise it stops there, as on main. After skipping a name it stops at the next explanatory comment.

With this branch:

$ isort - < example.py > sorted.py; cat sorted.py
from os.path import basename, dirname, join  # used below
from os.path import exists  # noqa: F401

print(basename, dirname, join)
$ isort --check - < sorted.py
$ flake8 --select F401 sorted.py

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.py changed on the second run (# type: ignore[attr-defined] moved onto POINTER, Structure), and with the black profile pendulum's helpers.py changed as well.

Testing

  • Two parametrized tests in 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 on main; the other five cover the Copilot review points, which main already handles.
  • Full unit suite: 792 passed, 2 skipped. mypy, ruff check, ruff format --check, flake8 and bandit are clean.
  • About 1,900 real files (the test environment's site-packages plus truststore, pendulum, requests, urllib3, rich, attrs and pydantic), sorted twice with default settings and the black profile: on main 6 and 7 files change on the second run, with this branch none do.
  • 3,000 random import blocks with per-name comments under 14 configurations: the number of results that change on a second run goes from 12,243 on main to 5,734 (of 42,000 runs).

Known limits:

  • A module with aliases, or sorted with no_inline_sort or only_sections, does not get the compact grouping: names without comments after a conflicting comment go into a statement of their own.
  • A parenthesized import under the black profile with combine_as_imports, such as (a as aa, # noqa / b, # explanation / c,), still changes on the second run, as on main.
  • When two imports bind the same name, sorting with no_inline_sort, only_sections or force_sort_within_sections with length_sort can order them differently than main does. main does not keep their input order there either; the random test above changed what a name refers to in 8,509 runs on main and 8,496 with this branch.

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

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.90909% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 99.16%. Comparing base (841e431) to head (062f80d).
⚠️ Report is 14 commits behind head on main.

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:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

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 noqa placement.
  • 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

Comment thread isort/output.py Resolved
Comment thread isort/output.py Resolved
Comment thread isort/output.py Resolved
Comment thread isort/output.py Resolved
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>

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.

Comment thread isort/output.py Resolved
Comment thread isort/output.py Outdated
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
Comment thread isort/output.py Outdated
or (grouped_has_explanation and bool(pragma_comments))
)
if incompatible:
if preserve_order or any(
Comment thread isort/output.py Resolved
Comment thread isort/output.py Resolved
Comment thread isort/output.py Resolved
@PDGGK

PDGGK commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

I ran the six Copilot points against 062f80d, the first commit 3936b83, and main (eb62da3), with Python 3.13 in a container. Script below.

  1. profile="open_stack", from x import getX as bb then from x import get_x as bb # pylint: disable=x: main and 3936b83 keep the order; 062f80d swaps the two lines, so bb ends up as x.getX.
  2. multi_line_output=NOQA, line_length=30, from x import getX # type: ignore[attr-defined]: main and 3936b83 give from x import getX # type: ignore[attr-defined] # NOQA; 062f80d gives from x import getX # NOQA type: ignore[attr-defined], which mypy no longer reads as an ignore.
  3. a # explanation, a as c, b # type: ignore, c from x: since 3936b83 the output is from x import a, c # explanation, from x import a as c, from x import b # type: ignore, so c is x.a. main keeps x.c for this input, but main is not idempotent on it, and main already rebinds c for from x import c followed by from x import a as c without any comments.
  4. ignore_comments=True, no_inline_sort=True on a # one, b as bb, c # two, a as aa: 062f80d writes four lines and joins a, c on the second run; main and 3936b83 are idempotent.
  5. combine_as_imports=True on from x import ( # explanation / a as aa, / b as bb, # noqa: F401 / ): since 3936b83 the first run splits it into two lines and the second run joins them again; main is idempotent.
  6. N single-name imports, each with # type: ignore, for N = 100/200/400: main 0.001/0.002/0.005 s, 3936b83 0.001/0.003/0.008 s, 062f80d 0.013/0.088/0.646 s.

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.

Script
import 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")

@DanielNoord

Copy link
Copy Markdown
Member

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 10.0.0.
However, I have also grown slightly concerned about the size of the diff that was introduced by my agent and wanted to look into that later.

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?

Reverts 062f80d and 3936b83, so that the next commits can redo the fix on top of main with a smaller change.
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.
@PDGGK

PDGGK commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

Here is a smaller version, redone on top of current main: isort/output.py +24/−3, no change to parse.py, and two parametrized tests.

It keeps the approach of my first commit, with these changes:

  • A later statement for a module stops at any comment instead of skipping over it, so it holds either one commented name or names without comments.
  • The first statement skips a name whose pragma comment it cannot share only when the module has no aliases and its names are sorted; otherwise it stops there, as on main. After a skip it stops at the next explanatory comment.
  • It no longer counts the combine_as_imports comments while grouping, and only the explode check treats a later noqa name like other commented names, so the NOQA formatter is unchanged.

With this, points 1, 2, 4 and 5 give the same output as main, 3 keeps the input layout and what c refers to, and 6 is linear again (800 # type: ignore imports in 0.009 s, as on main). I rewrote the description to match, including the limits that remain.

So that nothing of yours is lost, I pushed it on top of 062f80d as a revert of both earlier commits, a merge of main, and the new commit (1d1150d); the PR diff is now the small change only. I can squash it into a single commit if you prefer.

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

Black-profile wrapping still hoists a later import’s noqa pragma, making sorted output non-idempotent and causing --check to fail immediately after sorting.

3 open issues
4 resolved since last review

Review effort: Balanced

Comment thread isort/output.py
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)

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.

3 participants