Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions docs/configuration/options.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion isort/_parse_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:]]
)
Expand Down
5 changes: 5 additions & 0 deletions isort/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 3 additions & 1 deletion isort/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
9 changes: 8 additions & 1 deletion isort/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions isort/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 41 additions & 1 deletion isort/wrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -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,
Expand Down
149 changes: 149 additions & 0 deletions tests/unit/test_wrap_long_from_imports.py
Original file line number Diff line number Diff line change
@@ -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