isort icon indicating copy to clipboard operation
isort copied to clipboard

force_grid_wrap + include_trailing_comma can rewrite a from-import into invalid Python

Open simpleqt opened this issue 1 month ago • 0 comments

With force_grid_wrap and include_trailing_comma, isort can rewrite a valid from ... import statement into invalid Python.

>>> import isort
>>> isort.code(
...     "from mymodule.sub import y2, long_name\n",
...     force_grid_wrap=2, include_trailing_comma=True, use_parentheses=True, line_length=40,
... )
'from mymodule.(\n    sub import (long_name, y2,),)\n'

That output raises SyntaxError. With use_parentheses=False the same statement is split inside the module path instead, so the requested grid layout is lost.

Versions: current main (a514c71e) and released 9.0.2 — long-standing, not a 10.0 regression.

Why: with those options the grid formatter returns a single line that is one character over line_length, because its own length check does not account for the trailing comma appended afterwards (isort/wrap_modes.py:70 vs :93). wrap.import_statement() then hands that already-parenthesised statement back to wrap.line(), which cannot split at the import keyword (it is followed by () and falls back to its . splitter, parenthesising the remainder behind the dot of the module path.

Expected either the requested grid layout:

from mymodule.sub import (
    long_name, y2,)

or at minimum a statement that is valid Python and a fixpoint of a second isort.code() run.

I have a fix with a regression test for this - the statement is left alone when it already carries the wrap mode's parentheses, so the existing GRID fallback in output.sorted_imports() emits the vertical grid layout. I will open a pull request for it; this issue is to make sure nobody else is on it already.

simpleqt avatar Oct 24 '26 17:10 simpleqt