Fix unindented comments being corrupted in indented blocks#2459
Merged
DanielNoord merged 1 commit intoPyCQA:mainfrom Feb 19, 2026
Merged
Conversation
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 PyCQA#1899
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #2459 +/- ##
=======================================
Coverage 99.24% 99.24%
=======================================
Files 39 39
Lines 3057 3057
Branches 675 675
=======================================
Hits 3034 3034
Misses 13 13
Partials 10 10 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
When an unindented comment appears before an indented import block, isort corrupts the comment by stripping
len(indent)characters from the start of every line—even lines that don't begin with that indent.Before fix:
After fix: The comment is preserved correctly.
Root cause
In
isort/core.pyline 422, the indent-stripping logic:blindly slices every line without checking if it actually starts with the indent prefix.
Fix
Added a
line.startswith(indent)guard so only properly indented lines get stripped:Test plan
test_unindented_comment_in_indented_block_issue_1899totests/unit/test_ticketed_features.pyFixes #1899
🤖 Generated with Claude Code