Skip to content

fix(sorting): keep length_sort in length order under native sort_order - #2778

Open
simpleqt wants to merge 1 commit into
PyCQA:mainfrom
simpleqt:fix/length-sort-native-order
Open

simpleqt wants to merge 1 commit into
PyCQA:mainfrom
simpleqt:fix/length-sort-native-order

Conversation

@simpleqt

@simpleqt simpleqt commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

fix(sorting): keep length_sort in length order under native sort_order

Fixes #2698.

The problem

With length_sort=True and sort_order="native", imports are no longer ordered by length: the
sort key embeds the length as an unpadded decimal string (str(len(name)) + ":" + name in
isort/sorting.py, module_key; plain len(line) in section_key), and the native sort order
compares those keys with plain lexicographic sorted(). String comparison puts "10:" before
"9:", so longer imports come first once name lengths cross a digit boundary:

$ python -c "import isort; print(isort.code('import i\nimport bbbbbbbbbb\n', length_sort=True, sort_order='native'))"
import bbbbbbbbbb
import i

With the default sort_order="natural" the same input sorts correctly (i first), because
naturally() converts digit runs to integers via _natural_keys. The bug affects every length
path: straight imports, length_sort_straight, from-import member names,
length_sort_sections, force_sort_within_sections (via section_key), and reverse_sort
(which reverses the wrong order).

The input above carries no comments and no exotic syntax, so the defect does not depend on any
comment or docstring content.

The fix

Zero-pad the embedded length to a fixed width of six digits in both module_key and
section_key, so lexicographic key order equals numeric length order under plain sorted()
while naturally() keeps producing identical keys after int() strips the zeros:

_length_sort_maybe = (
    str(len(module_name)).zfill(6) + module_name if length_sort else module_name
)

Six digits cover any import line up to 999,999 characters; beyond that the key contains more
digits than the width and those entries only compare among themselves unpadded (same shape as
the pre-fix behavior, unreachable in practice).

This keeps the string-key interface that sorting plugins rely on (only the sort_order="native"
path, which is builtin sorted, changes output), and preserves the documented native
lexicographic ordering of module names for equal-length imports (see
test_sort_configurable_sort_issue_1732).

Why not the previously attempted padding

#2703 padded to str(sys.maxsize) width (19 digits) and was closed after review asked for
benchmarks showing it did not slow sorting down (~9% full-pipeline slowdown was measured on that
approach). This patch pads to six digits using str().zfill() instead of a format-spec
f-string, which benchmarks at parity:

  • Key generation micro-benchmark (verbatim copy of the old module_key vs the new one, same
    process, 200 reps x 9, best-of, 1000 module names, Windows / CPython 3.11):
    old 225.7 ms vs new 215.2 ms per run - parity (within run-to-run noise).
  • Full pipeline with the review benchmark from fix(sorting): preserve length order with native sorting #2703
    (isort.code of 1000 generated imports, length_sort=True, sort_order="native",
    number=30, repeat=7, best-of, median of 3 runs): main ~700 ms vs patched ~703 ms - parity.
    The unmodified paths (sort_order default, no length_sort) also show no change.

Behavior verification

A differential run over 120 deterministic 3-module import blocks and from-import blocks crossed
with 20 option sets (2520 cases) against main@5d9c9619:

  • 2120 cases byte-identical (every case without both sort_order="native" and a length flag).
  • 400 changed cases, all 400 confined to option sets containing both sort_order="native" and
    length_sort / length_sort_straight / length_sort_sections - exactly the intended scope,
    with the patched output in nondecreasing import-name length order.

Test

tests/unit/test_isort.py::test_length_sort_native_order_issue_2698 covers straight imports,
reverse_sort, force_sort_within_sections (the section_key path), length_sort_straight,
and from-import member names at a digit boundary (lengths 1, 8, 10). Red on main, green with
this patch. Full suite: 741 passed, 9 skipped (2 collection errors from missing optional deps
in the local environment were resolved by installing the repo example plugins and
pytest-benchmark; unrelated to this change).

Proposed issue text

A companion issue already exists: #2698 ("length_sort with native sort order puts a longer
import first"). Do not file a new issue; reference #2698 in the PR ("Fixes #2698") and, if a
comment is wanted when submitting, paste:

I have a fix for this ready. Unlike the earlier attempt in #2703 (closed for the ~9% slowdown
from 19-digit zero-padding), it pads the length to a fixed six digits with str().zfill(),
which benchmarks at parity with main both on key generation and on the full pipeline, while
restoring length order under sort_order="native" for straight imports, from-import members,
length_sort_sections, force_sort_within_sections, and reverse_sort. PR incoming.

Copilot AI balanced review requested due to automatic review settings November 1, 2026 15:48

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@codecov

codecov Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.40%. Comparing base (48674a7) to head (e727430).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2778   +/-   ##
=======================================
  Coverage   99.40%   99.40%           
=======================================
  Files          40       40           
  Lines        3367     3368    +1     
  Branches      726      726           
=======================================
+ Hits         3347     3348    +1     
  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.

Is there no better solution to this? This feels very hacky.

@simpleqt

simpleqt commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Good question. The constraint is that module_key/section_key return the string key that is handed to arbitrary sorting_function plugins, so switching to a tuple (length, name) would change that plugin-facing contract. To keep a string key, the numeric length has to be embedded at a fixed width; 6 digits covers any import line up to 999,999 characters. The previous attempt (#2703) padded to the width of sys.maxsize and measured ~9–20% key-generation overhead, while the six-digit prefix stays near parity (+0.4% in the PR benchmark). The more structural alternative is a separate native+length sort that orders by (len, key) before the configured function, but it needs a per-call-site length callback because the key function rewrites relative imports and section prefixes — a larger change to the plugin path. Happy to implement that instead if you prefer it.

The sort keys built by module_key and section_key embed the import length
as an unpadded decimal string, so with sort_order="native" (plain
lexicographic sorted) "10:" compares before "9:" and longer imports
come first once name lengths cross a digit boundary. The default natural
order was unaffected because naturally() converts digit runs to ints.

Zero-pad the embedded length to six digits so lexicographic key order
equals numeric length order under both sorting functions. Six digits
cover any realistic import line; natural-order keys are unchanged after
int() strips the zeros, and sorting plugins keep receiving string keys.

Fixes PyCQA#2698

Signed-off-by: simpleqt <2015900818@qq.com>
@simpleqt
simpleqt force-pushed the fix/length-sort-native-order branch from 319728a to e727430 Compare December 3, 2026 06:23
@simpleqt

simpleqt commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

I also rebased this onto current main (e727430, base 48674a7) because the branch had become unmergeable while the review was pending. The only conflict was module_key: I kept the new force_to_top index prefix from main and applied the length padding after it. pytest tests/unit -q: 784 passed, 75 skipped.

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.

length_sort with native sort order puts a longer import first

3 participants