From fee6e8eafd28118e33e47f5425e0f4edcb1537a7 Mon Sep 17 00:00:00 2001 From: Matan Perelman Date: Thu, 11 Sep 2025 17:58:49 +0300 Subject: [PATCH] Fix output of hanging indent for long lines with noqa --- isort/output.py | 11 +++++++++++ tests/unit/test_isort.py | 13 +++++++++++++ 2 files changed, 24 insertions(+) diff --git a/isort/output.py b/isort/output.py index 65a6ff7ee..3dbcdc48d 100644 --- a/isort/output.py +++ b/isort/output.py @@ -454,6 +454,17 @@ def _with_from_imports( parsed.categorized_comments["nested"].get(module, {}).pop(from_import, None) ) if comment: + # If the comment is a noqa and hanging indent wrapping is used, + # keep the name in the main list and hoist the comment to the statement. + if ( + comment.lower().startswith("noqa") + and config.multi_line_output + == wrap.Modes.HANGING_INDENT # type: ignore[attr-defined] + ): + comments = list(comments) if comments else [] + comments.append(comment) + continue + from_imports.remove(from_import) if from_imports: use_comments = [] diff --git a/tests/unit/test_isort.py b/tests/unit/test_isort.py index e72f1fee1..199d565f3 100644 --- a/tests/unit/test_isort.py +++ b/tests/unit/test_isort.py @@ -5741,3 +5741,16 @@ def test_reexport_multiline_long_rollback() -> None: test """ assert isort.code(test_input, config=Config(sort_reexports=True)) == expd_output + + +def test_noqa_multiline_hanging_indent() -> None: + test_input = ( + "from aaaaaaa import bbbbbbbbbbbbbbbbb, ccccccccccccccccccc, dddddddddddddddd" + "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, \\\n" + " fffffffffffffffffffff # noqa: E402\n" + "\n" + "print(fffffffffffffffffffff)\n" + "print(dddddddddddddddd)\n" + ) + output = isort.code(test_input, line_length=120, multi_line_output=WrapModes.HANGING_INDENT) + assert output == test_input