Skip to content

Sort template-written imports with their comments like isort - #6677

Merged
Koudai Aono (koxudaxi) merged 1 commit into
bfmt-9from
bfmt-10
Nov 10, 2026
Merged

Koudai Aono (koxudaxi) merged 1 commit into
bfmt-9from
bfmt-10

Conversation

@koxudaxi

@koxudaxi Koudai Aono (koxudaxi) commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Fixes: #6668

Summary by CodeRabbit

  • Bug Fixes
    • Improved import formatting to keep comments associated with the correct imports and place other comments consistently.
    • Import sorting now also works within nested code blocks.
    • Formatting is more reliable when imports appear alongside other statements, preserving existing code and imported names.

@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The built-in formatter now keeps comments associated with module imports, sorts import runs after module statements, and places moved comments after the module import block. New tests check formatting against isort and Black, preservation of imports and non-import statements, idempotence, and same-line import behavior.

Changes: Built-in Formatter Import Handling

Layer / File(s) Summary
Associate comments with module imports
src/datamodel_code_generator/_builtin_formatter.py
The formatter associates comments with their source imports and carries those associations into the formatted import block.
Format import runs and place moved comments
src/datamodel_code_generator/_builtin_formatter.py, tests/test_format.py
The formatter sorts nested and top-level import runs after module statements and places moved comments after the main import block. Tests check output preservation, idempotence, and imports sharing a line with a statement.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related PRs

Suggested labels: breaking-change-analyzed

Merge Risk: Minimal · up to 123c4

The built-in formatter change sorts template-written imports and keeps their comments. No concrete merge-blocking risk was identified, and the new tests cover isort/Black parity and idempotence.

Pre-merge checks: Passed 5

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly describes the main change: sorting template-written imports while preserving their comments, consistent with the formatter changes and linked issue.
Linked Issues check Passed Issue #6668 requires preserving comments above imports and sorting import runs after the first class with isort-style grouping. The formatter now keeps comments with their associated module imports an…
Out of Scope Changes check Passed The formatter changes support comment preservation and sorting imports written after module statements. The added tests validate those behaviors. The import-index and blank-line handling changes suppo…
Docstring Coverage Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentati…
Full details: Linked Issues check

Explanation

Issue #6668 requires preserving comments above imports and sorting import runs after the first class with isort-style grouping. The formatter now keeps comments with their associated module imports and sorts import runs in nested statement bodies. The added tests cover imports interleaved with module statements and comments, compare output with isort followed by Black, and check preservation and idempotence.

Full details: Out of Scope Changes check

Explanation

The formatter changes support comment preservation and sorting imports written after module statements. The added tests validate those behaviors. The import-index and blank-line handling changes support keeping comments attached and placing them correctly; no unrelated change appears in the supplied summary.

Full details: Docstring Coverage

Explanation

Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 12 functions across 2 files.

Finishing Touches

Generate docstrings

  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between dd4eb97 and 123c4b2.

Files ignored due to path filters: 1

  • tests/data/expected/builtin_formatter/generated_edge_cases.txt is excluded by !tests/data/**/*.txt and included by none
Files selected for processing: 2

  • src/datamodel_code_generator/_builtin_formatter.py
  • tests/test_format.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T09:45:46.873561Z 123c4b2 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

Copy link
Copy Markdown
Contributor

@codspeed

codspeed Bot commented Nov 10, 2026

Copy link
Copy Markdown

Merging this PR will degrade performance by 15.5%

1 warning

⚠️ Walltime results may be unreliable

Some benchmarks used the Walltime instrument outside CodSpeed Macro Runners, which can make the results inconsistent.

Learn more about Macro Runners

See affected benchmarks

⚡ 1 improved benchmark
❌ 10 regressed benchmarks
✅ 42 untouched benchmarks
⏩ 98 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_perf_target_render[fastapi-small] 17.9 ms 26.7 ms -32.8%
❌ test_perf_stripe_style_pydantic_v2 1.4 s 1.8 s -24.53%
❌ test_perf_recommend_options_full_kubernetes_style 15.6 s 19.5 s -19.99%
❌ test_perf_false_reference_validation 279.6 ms 338.9 ms -17.5%
❌ test_perf_aws_style_openapi_pydantic_v2 1.3 s 1.5 s -15.84%
❌ test_perf_inherited_required_fields[required-base-first] 425.4 ms 498.3 ms -14.63%
❌ test_perf_target_render[fastapi-large] 5.2 s 6 s -14.43%
❌ test_perf_inherited_required_fields[required-derived-first] 475.6 ms 552.9 ms -13.99%
❌ test_perf_target_render[client-large] 8.6 s 10 s -13.13%
❌ test_perf_inherited_required_fields[partial-derived-first] 853.5 ms 956.5 ms -10.77%
⚡ test_perf_simple_pydantic_v2_field_construction 6.9 ms 6.1 ms +14.26%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing bfmt-10 (123c4b2) with main (b9e468d)2

Open in CodSpeed

Footnotes

  1. 98 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

  2. No successful run was found on bfmt-9 (dd4eb97) during the generation of this report, so main (b9e468d) was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@koxudaxi
Koudai Aono (koxudaxi) merged commit 0a6deba into main Nov 10, 2026
41 of 144 checks passed
@koxudaxi
Koudai Aono (koxudaxi) deleted the bfmt-10 branch November 10, 2026 15:42
@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: The PR only changes the private module _builtin_formatter.py plus its tests and one expected-output fixture. It makes the built-in formatter match isort and black more closely. Comments directly above an import in the module import block now move with that import, and other comments between imports move below the block where they used to be lost. Import runs at module level after the first statement are now sorted, as isort already does for nested bodies. A compound line such as an import followed by a semicolon and another statement now keeps that second statement instead of silently dropping it, which is what the changed fixture shows. All signature changes are on private underscore helpers such as _BlankLinePlacer, _iter_aliased_from_import_lines and _build_builtin_import_block, whose new keyword argument is optional and defaults to the old behaviour. No public CLI option, Python API, template variable or supported Python version is added, removed or changed. Every behaviour diff gate cell is classed both-fail, with no accepted or violation cells, so default generated output is unchanged. Any remaining output differences only affect unusual input such as custom templates with comments between imports, and they fix lost comments or code rather than break existing users.


This analysis was produced by the release draft workflow

@github-actions

Copy link
Copy Markdown
Contributor

🎉 Released in 0.93.0

This PR is now available in the latest release. See the release notes for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Builtin formatter mishandles imports that a custom template writes

1 participant