Skip to content

Commit fd2514b

Browse files
Fridayclaude
andcommitted
Fix unindented comments being corrupted in indented blocks
When an unindented comment appears before an indented import block, isort blindly strips `len(indent)` characters from the start of every line. This corrupts comments that don't start with the expected indent. For example: ```python if True: # this will get cut off import os ``` became: ```python if True: is will get cut off import os ``` The fix checks whether each line actually starts with the indent before stripping it. Fixes #1899 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent b0f2dab commit fd2514b

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

isort/core.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,8 @@ def process(
420420

421421
if indent:
422422
import_section = "".join(
423-
line[len(indent) :] for line in import_section.splitlines(keepends=True)
423+
line[len(indent) :] if line.startswith(indent) else line
424+
for line in import_section.splitlines(keepends=True)
424425
)
425426

426427
parsed_content = parse.file_contents(import_section, config=config)

tests/unit/test_ticketed_features.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1073,3 +1073,17 @@ def use_libc_math():
10731073
""",
10741074
show_diff=True,
10751075
)
1076+
1077+
1078+
def test_unindented_comment_in_indented_block_issue_1899():
1079+
"""Test that unindented comments before indented imports are not corrupted.
1080+
1081+
See: https://github.com/PyCQA/isort/issues/1899
1082+
"""
1083+
test_input = """import sys
1084+
1085+
if True:
1086+
# this will get cut off
1087+
import os
1088+
"""
1089+
assert isort.code(test_input) == test_input

0 commit comments

Comments
 (0)