From e93ff8258df56a24ad8e0b3a854f2a55837e94ba Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Sun, 22 Nov 2026 06:00:56 +0800 Subject: [PATCH 1/4] Add opt-in wrapping for long from-import paths --- isort/_parse_utils.py | 2 +- isort/main.py | 5 +++++ isort/output.py | 4 +++- isort/parse.py | 9 ++++++++- isort/settings.py | 1 + isort/wrap.py | 42 +++++++++++++++++++++++++++++++++++++++++- 6 files changed, 59 insertions(+), 4 deletions(-) diff --git a/isort/_parse_utils.py b/isort/_parse_utils.py index fd0f8a3ed..72e6a7683 100644 --- a/isort/_parse_utils.py +++ b/isort/_parse_utils.py @@ -161,7 +161,7 @@ def normalize_from_import_string(import_string: str) -> str: ) cimports = " cimport " in import_string parts = import_string.split(" cimport " if cimports else " import ") - from_import = parts[0].split(" ") + from_import = parts[0].split() return (" cimport " if cimports else " import ").join( [from_import[0] + " " + "".join(from_import[1:]), *parts[1:]] ) diff --git a/isort/main.py b/isort/main.py index d04794008..519c0d607 100644 --- a/isort/main.py +++ b/isort/main.py @@ -639,6 +639,11 @@ def _build_arg_parser() -> argparse.ArgumentParser: " **NOTE**: This is separate from wrap modes, and only affects how individual lines that " " are too long get continued, not sections of multiple imports.", ) + output_group.add_argument( + "--wrap-long-from-imports", + action="store_true", + help="Wrap long dotted module paths in from imports using backslashes.", + ) output_group.add_argument( "-l", "-w", diff --git a/isort/output.py b/isort/output.py index 5c32f718c..67d19b68e 100644 --- a/isort/output.py +++ b/isort/output.py @@ -307,7 +307,9 @@ def _build_import_group( group_output.extend(line_comments) group_output.append(line) - return group_output + return [ + wrap.module_path(statement, parsed.line_separator, config) for statement in group_output + ] def _build_as_imports( diff --git a/isort/parse.py b/isort/parse.py index 7de26bbe9..73aa47362 100644 --- a/isort/parse.py +++ b/isort/parse.py @@ -243,7 +243,14 @@ def _get_next_line() -> tuple[str, str | None]: # If during parsing of the continuation lines we encounter a comment, we record it. if extra_line.comment is not None: comments.append(extra_line.comment) - stripped_line = strip_syntax(extra_line.line).strip() + commented_line = extra_line.line + if type_of_import is _ImportType.FROM: + # A continued module path can end on this line, before + # the commented imported name (including a star). + commented_line = commented_line.split(" import ", 1)[-1].split( + " cimport ", 1 + )[-1] + stripped_line = strip_syntax(commented_line).strip() if ( type_of_import is _ImportType.FROM and stripped_line diff --git a/isort/settings.py b/isort/settings.py index 275579c89..9eeab8dba 100644 --- a/isort/settings.py +++ b/isort/settings.py @@ -173,6 +173,7 @@ class _Config: import_footers: dict[str, str] = field(default_factory=dict) balanced_wrapping: bool = False use_parentheses: bool = False + wrap_long_from_imports: bool = False order_by_type: bool = True atomic: bool = False lines_before_imports: int = -1 diff --git a/isort/wrap.py b/isort/wrap.py index 7fdb5de31..8ab9628ae 100644 --- a/isort/wrap.py +++ b/isort/wrap.py @@ -12,6 +12,45 @@ def _is_wrapped(statement: str) -> bool: return "(" in statement.split("#", 1)[0] +def module_path(statement: str, line_separator: str, config: Config) -> str: + """Optionally wrap the dotted module path of a completed from-import statement.""" + if not config.wrap_long_from_imports or config.multi_line_output is Modes.NOQA: + return statement + + return line_separator.join( + _module_path_line(line, line_separator, config) for line in statement.split(line_separator) + ) + + +def _module_path_line(content: str, line_separator: str, config: Config) -> str: + match = re.fullmatch(r"((?:lazy )?from )(\S+)( (?:cimport|import)\b.*)", content) + if match is None: + return content + + prefix, module, suffix = match.groups() + keyword = suffix.split(" ", 2)[1] + if len(prefix + module + " " + keyword) <= config.line_length: + return content + + line_length = config.wrap_length or config.line_length + lines = [] + while len(prefix + module + suffix) > line_length: + # Keep the relative-import dots together and leave room for the backslash. + relative_dots = len(module) - len(module.lstrip(".")) + split_at = module.rfind(".", relative_dots, max(line_length - len(prefix) - 1, 0)) + if split_at < 0: + # A single component may be longer than the limit; never split an identifier. + split_at = module.find(".", relative_dots) + if split_at < 0: + break + lines.append(prefix + module[: split_at + 1] + "\\") + module = module[split_at + 1 :] + prefix = config.indent + + lines.append(prefix + module + suffix) + return line_separator.join(lines) + + def import_statement( import_start: str, from_imports: list[str], @@ -30,7 +69,8 @@ def import_statement( formatter = formatter_from_string((multi_line_output or config.multi_line_output).name) line_length = config.wrap_length or config.line_length include_trailing_comma = config.include_trailing_comma - dynamic_indent = " " * (len(import_start) + 1) + wrapped_start = module_path(import_start, line_separator, config) + dynamic_indent = " " * (len(wrapped_start.rsplit(line_separator, 1)[-1]) + 1) indent = config.indent statement = formatter( statement=import_start, From 2da905c3d8492bdc48834f294cc060ace5a292c5 Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Sun, 22 Nov 2026 06:02:25 +0800 Subject: [PATCH 2/4] Cover long module wrapping and comment retention --- tests/unit/test_wrap_long_from_imports.py | 149 ++++++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 tests/unit/test_wrap_long_from_imports.py diff --git a/tests/unit/test_wrap_long_from_imports.py b/tests/unit/test_wrap_long_from_imports.py new file mode 100644 index 000000000..af7d87d51 --- /dev/null +++ b/tests/unit/test_wrap_long_from_imports.py @@ -0,0 +1,149 @@ +import ast +from pathlib import Path + +import pytest + +import isort +from isort import main +from isort.settings import Config +from isort.wrap_modes import WrapModes + +MODULE = "package.subpackage.component.another_component.final_module" + + +def assert_valid_and_stable(source: str, config: Config) -> str: + output = isort.code(source, config=config) + default_output = isort.code(source, config=Config(config=config, wrap_long_from_imports=False)) + assert ast.dump(ast.parse(output)) == ast.dump(ast.parse(default_output)) + assert isort.code(output, config=config) == output + return output + + +def test_long_from_import_issue_1531() -> None: + source = ( + "from monkey_island.cc.services.zero_trust.scoutsuite.data_parsing." + "rule_path_building.rule_path_creators.vpc_rule_path_creator import \\\n" + " VPCRulePathCreator\n" + ) + assert isort.code(source, line_length=120) == source + + output = assert_valid_and_stable(source, Config(line_length=120, wrap_long_from_imports=True)) + assert max(map(len, output.splitlines())) <= 120 + assert ".\\\n" in output + + +@pytest.mark.parametrize("mode", [mode for mode in WrapModes if mode is not WrapModes.NOQA]) +def test_long_from_import_wrap_modes(mode: WrapModes) -> None: + source = f"from {MODULE} import alpha, beta, gamma\n" + output = assert_valid_and_stable( + source, Config(line_length=40, multi_line_output=mode, wrap_long_from_imports=True) + ) + assert ".\\\n" in output + assert max(map(len, output.splitlines())) <= 40 + + +@pytest.mark.parametrize("use_parentheses", [False, True]) +@pytest.mark.parametrize( + "imported", + [ + "alpha", + "alpha as alias", + "alpha # comment", + "alpha as alias # noqa: F401", + "*", + "* # star comment", + "* # noqa: F403", + "* # type: ignore", + ], +) +def test_long_from_import_comments_and_aliases(imported: str, use_parentheses: bool) -> None: + source = f"from {MODULE} import {imported}\n" + output = assert_valid_and_stable( + source, + Config( + line_length=40, + use_parentheses=use_parentheses, + wrap_long_from_imports=True, + ), + ) + assert ".\\\n" in output + assert output.count("#") == source.count("#") + assert all(not line.rstrip().endswith("\\") or "#" not in line for line in output.splitlines()) + + +def test_long_from_import_relative_and_indented() -> None: + source = f"def function():\n from ...{MODULE} import alpha\n" + output = assert_valid_and_stable(source, Config(line_length=40, wrap_long_from_imports=True)) + assert "from ...package." in output + assert ".\\\n " in output + assert max(map(len, output.splitlines())) <= 40 + + +def test_long_from_import_wrap_length_and_line_ending() -> None: + source = f"from {MODULE} import alpha, beta\r\n" + output = assert_valid_and_stable( + source, + Config(line_length=50, wrap_length=35, wrap_long_from_imports=True), + ) + assert ".\\\r\n" in output + assert max(map(len, output.splitlines())) <= 35 + + +@pytest.mark.parametrize( + "source", + ["from short.module import alpha\n", f"from {'x' * 80} import alpha\n"], +) +def test_long_from_import_unneeded_or_unbreakable(source: str) -> None: + config = Config(line_length=40, wrap_long_from_imports=True) + output = assert_valid_and_stable(source, config) + assert output == isort.code(source, line_length=40) + + +def test_long_from_import_noqa_mode() -> None: + source = f"from {MODULE} import alpha\n" + output = assert_valid_and_stable( + source, + Config(line_length=40, multi_line_output=WrapModes.NOQA, wrap_long_from_imports=True), + ) + assert output == isort.code(source, line_length=40, multi_line_output=WrapModes.NOQA) + + +def test_long_from_import_cli(tmp_path: Path) -> None: + source = f"from {MODULE} import alpha\n" + source_file = tmp_path / "module.py" + source_file.write_text(source) + args = [str(source_file), "--line-length", "40", "--wrap-long-from-imports"] + + main.main(args) + output = source_file.read_text() + assert ".\\\n" in output + assert ast.dump(ast.parse(output)) == ast.dump(ast.parse(source)) + main.main([*args, "--check-only"]) + assert source_file.read_text() == output + + +def test_long_from_import_config_file(tmp_path: Path) -> None: + config_file = tmp_path / "pyproject.toml" + config_file.write_text("[tool.isort]\nline_length = 40\nwrap_long_from_imports = true\n") + config = Config(settings_file=str(config_file)) + assert config.wrap_long_from_imports + output = assert_valid_and_stable(f"from {MODULE} import alpha\n", config) + assert ".\\\n" in output + + +@pytest.mark.parametrize(("prefix", "keyword"), [("lazy from", "import"), ("from", "cimport")]) +def test_long_from_import_other_syntax(prefix: str, keyword: str) -> None: + # The running interpreter need not support lazy imports or Cython syntax. + source = f"{prefix} {MODULE} {keyword} alpha\n" + config = Config(line_length=40, wrap_long_from_imports=True) + output = isort.code(source, config=config) + assert ".\\\n" in output + assert isort.code(output, config=config) == output + assert isort.code(output) == isort.code(source) + + +def test_long_from_import_long_component() -> None: + source = f"from {'x' * 80}.package.module import alpha\n" + output = assert_valid_and_stable(source, Config(line_length=40, wrap_long_from_imports=True)) + assert f"from {'x' * 80}.\\\n" in output + assert "package.module import" in output From 597792226de8416e243916ab370d3772125c86c7 Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Sun, 22 Nov 2026 06:05:40 +0800 Subject: [PATCH 3/4] Document long from-import wrapping --- docs/configuration/options.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/docs/configuration/options.md b/docs/configuration/options.md index 10ccf832d..4b07f46a9 100644 --- a/docs/configuration/options.md +++ b/docs/configuration/options.md @@ -812,6 +812,37 @@ Use parentheses for line continuation on length limit instead of backslashes. ** - --up - --use-parentheses +## Wrap Long From Imports + +Allow the dotted module path in a `from` import to wrap when the module and import keyword +exceed `line_length`. Splits occur after dots, using backslashes and the configured indent. +Wrapped lines use `wrap_length` when it is set. Individual identifiers and the leading dots +of a relative import are kept together, so an unusually long identifier may still exceed +the limit. + +This option is disabled by default. Module paths always need backslashes, even when +`use_parentheses` or a parenthesized multi-line output mode is used for the imported names. +The `NOQA` output mode keeps its existing behavior instead of wrapping the module path. +Other formatters, including Black, may join these module paths again. + +**Type:** Bool + +**Default:** `False` + +**Config default:** `false` + +**Python & Config File Name:** wrap_long_from_imports + +**CLI Flags:** + +- --wrap-long-from-imports + +For example, with `line_length=40` and `wrap_long_from_imports=true`: + +```python +from package.subpackage.component.another_component.final_module import alpha +``` + ## Order By Type Order imports by type, which is determined by case, in addition to alphabetically. From cdfbb63e51c4c946b5c04deb7c23397d19a62480 Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Sun, 22 Nov 2026 06:06:15 +0800 Subject: [PATCH 4/4] Note the optional module-path wrapping setting --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f88ce198..3a47e6680 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ on [Github](https://github.com/PyCQA/isort/releases). ### Unreleased + - Add the opt-in `wrap_long_from_imports` setting to wrap long dotted module paths in from imports (#1531). + ### 9.0.0 August 26 2026 - Remove logic for deprecated options (#2498) @DanielNoord