Skip to content

Preserve blank lines between pre-import code and first import#441

Closed
Childcity wants to merge 1 commit into
asottile:mainfrom
Childcity:dont-touch-new-lines-before-imports
Closed

Preserve blank lines between pre-import code and first import#441
Childcity wants to merge 1 commit into
asottile:mainfrom
Childcity:dont-touch-new-lines-before-imports

Conversation

@Childcity

Copy link
Copy Markdown

Previously, blank lines (NON_CODE tokens) that appeared between the last pre-import block (docstring, shebang, encoding comment) and the first import statement were silently dropped by partition_source().

This was inconsistent with Black, which keeps such blank lines intact.

Root cause: the loop building pre/imports/code only added NON_CODE chunks to 'code' when i > last_idx. Blank lines before last_idx were simply discarded.

Fix: track last_pre_import_idx (index of the last PRE_IMPORT_CODE chunk) and first_import_idx (index of the first IMPORT chunk). NON_CODE chunks that fall strictly between those two positions are now appended to 'pre', preserving the original blank lines.

Blank lines between pre-import comments (before the docstring boundary) are still stripped, as are blank lines between import statements themselves -- only the gap between the pre-import block and the first import is preserved.

Previously, blank lines (NON_CODE tokens) that appeared between the last
pre-import block (docstring, shebang, encoding comment) and the first
import statement were silently dropped by partition_source().

This was inconsistent with Black, which keeps such blank lines intact.

Root cause: the loop building pre/imports/code only added NON_CODE chunks
to 'code' when i > last_idx. Blank lines before last_idx were simply
discarded.

Fix: track last_pre_import_idx (index of the last PRE_IMPORT_CODE chunk)
and first_import_idx (index of the first IMPORT chunk). NON_CODE chunks
that fall strictly between those two positions are now appended to 'pre',
preserving the original blank lines.

Blank lines between pre-import comments (before the docstring boundary)
are still stripped, as are blank lines between import statements
themselves -- only the gap between the pre-import block and the first
import is preserved.
@asottile asottile closed this Jun 12, 2026
Repository owner locked as spam and limited conversation to collaborators Jun 12, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants