Skip to content

Keep comments between statements and place black's blank lines - #6675

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

Koudai Aono (koxudaxi) merged 1 commit into
bfmt-7from
bfmt-8

Conversation

@koxudaxi

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

Copy link
Copy Markdown
Member

Fixes: #6667
Fixes: #6669

Summary by CodeRabbit

  • Bug Fixes
    • Improved formatting consistency for blank lines and comments across imports, classes, control-flow blocks, and other statements.
    • Preserved comments in custom class templates and improved handling of modern type aliases.
    • Kept formatted code structurally unchanged and consistent across repeated formatting passes.

@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 places blank lines across statements, clauses, comments, and imports. Updated tests and expected outputs cover comment preservation and Black-compatible spacing.

Changes: Built-in formatter layout

Layer / File(s) Summary
Statement and import boundaries
src/datamodel_code_generator/_builtin_formatter.py
Statement traversal handles PEP 695 aliases and clause headers. Import replacements now cover only import runs.
Blank-line placement and formatter integration
src/datamodel_code_generator/_builtin_formatter.py, src/datamodel_code_generator/format.py
A blank-line placer handles logical lines, clauses, comments, and nesting. Formatter integration applies its replacements and skips duplicate top-level blank-line normalization. The removed helper is also removed from the formatter re-exports.
Formatting validation and expected outputs
tests/test_format.py, tests/main/jsonschema/*, tests/data/expected/main/jsonschema/*
Formatting tests cover comments, blank lines, AST preservation, and idempotence. JSON Schema expected outputs and reference mappings change, and a custom-template fixture covers class-body comments.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related PRs

Suggested labels: breaking-change-analyzed

Merge Risk: Minimal · up to 967c1

This change makes the built-in formatter keep comments between statements and place Black-style blank lines. No actionable merge-blocking risk was found, and the new test, its template and its expected output are present.

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 summarizes the main change: preserving comments between statements and applying Black-style blank-line placement in the built-in formatter.
Linked Issues check Passed The formatter changes implement the requested behavior in [#6667] and [#6669]. _BlankLinePlacer traverses comments and nested statements, preserves comment indentation, and places blank lines. The a…
Out of Scope Changes check Passed The import-handling refactor and blank-line placement changes support the formatter objectives in [#6667] and [#6669]. The generated fixture and test-reference updates align expected outputs with the …
Docstring Coverage Passed Docstring coverage is 82.61% 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

The formatter changes implement the requested behavior in [#6667] and [#6669]. _BlankLinePlacer traverses comments and nested statements, preserves comment indentation, and places blank lines. The added formatter tests compare comment placement and blank-line handling with Black, and the added custom-template test exercises class-body comments. The reviewed summary also reports handling for clause boundaries, nested classes, and top-level blank-line normalization. The excluded template path tests/data/templates/builtin_class_body_comments/pydantic_v2/BaseModel.jinja2 is not needed to establish these behaviors because the summary identifies the test scenario and the implementation and formatter tests provide independent evidence.

Full details: Out of Scope Changes check

Explanation

The import-handling refactor and blank-line placement changes support the formatter objectives in [#6667] and [#6669]. The generated fixture and test-reference updates align expected outputs with the changed formatter behavior. The summary does not establish any unrelated change.

Full details: Docstring Coverage

Explanation

Docstring coverage is 82.61% 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 23 functions across 3 files. (2 skipped: 1 unsupported, 1 too large.)

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 8ee69ef and 967c182.

Files ignored due to path filters: 1

  • tests/data/templates/builtin_class_body_comments/pydantic_v2/BaseModel.jinja2 is excluded by none and included by none
Files selected for processing: 18

  • src/datamodel_code_generator/_builtin_formatter.py
  • src/datamodel_code_generator/format.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/boolean_custom_False_False_builtin.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/boolean_custom_False_False_external.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/minimum_custom_False_False_builtin.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/minimum_custom_False_False_external.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/minimum_custom_False_True_builtin.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/minimum_custom_False_True_external.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/prefix_suffix_custom_False_False_builtin.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/prefix_suffix_custom_False_False_external.py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_builtin_formatter_keeps_custom_template_class_body_comments.py
  • tests/data/expected/main/jsonschema/pattern_intersections/single_custom_builtin.py
  • tests/data/expected/main/jsonschema/pattern_intersections/single_custom_disabled_builtin.py
  • tests/data/expected/main/jsonschema/undeclared_required/custom_objects_False_builtin.py
  • tests/data/expected/main/jsonschema/undeclared_required/custom_objects_False_external.py
  • tests/main/jsonschema/test_main_jsonschema.py
  • tests/main/jsonschema/test_main_jsonschema.refs
  • tests/test_format.py
Files with no reviewable changes: 13

  • src/datamodel_code_generator/format.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/boolean_custom_False_False_external.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/prefix_suffix_custom_False_False_external.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/minimum_custom_False_False_external.py
  • tests/data/expected/main/jsonschema/pattern_intersections/single_custom_builtin.py
  • tests/data/expected/main/jsonschema/undeclared_required/custom_objects_False_builtin.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/boolean_custom_False_False_builtin.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/minimum_custom_False_True_external.py
  • tests/data/expected/main/jsonschema/pattern_intersections/single_custom_disabled_builtin.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/prefix_suffix_custom_False_False_builtin.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/minimum_custom_False_False_builtin.py
  • tests/data/expected/main/jsonschema/undeclared_required/custom_objects_False_external.py
  • tests/data/expected/main/jsonschema/additional_pattern_intersections/minimum_custom_False_True_builtin.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 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:46:37.756313Z 967c182 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 33.6%

2 warnings

⚠️ 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

⚠️ 53 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

❌ 53 regressed benchmarks
⏩ 98 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_perf_load_yaml_openapi_large 17.5 ms 31.9 ms -45.06%
❌ test_perf_inherited_required_fields[partial-derived-first] 742.2 ms 1,258.7 ms -41.04%
❌ test_perf_large_models_pydantic_v2 1.9 s 3.1 s -40.39%
❌ test_perf_large_models_pydantic_v2_builtin 743.2 ms 1,243 ms -40.21%
❌ test_perf_false_reference_validation 248.7 ms 412.5 ms -39.7%
❌ test_perf_all_options_enabled 3.2 s 5.2 s -38.81%
❌ test_perf_openapi_large 1.7 s 2.8 s -38.58%
❌ test_perf_extreme_large_schema 8.3 s 13.4 s -38.21%
❌ test_perf_kubernetes_style_pydantic_v2 1.4 s 2.3 s -37.8%
❌ test_perf_unique_items_runtime_scalar_validation 1.5 ms 2.4 ms -37.75%
❌ test_perf_inherited_required_fields[partial-base-first] 703.8 ms 1,130.4 ms -37.74%
❌ test_perf_simple_pydantic_v2_field_construction 5.6 ms 8.9 ms -37.1%
❌ test_perf_ordinary_array_constraint_generation 1.1 s 1.7 s -36.99%
❌ test_perf_complex_refs 1.2 s 1.9 s -36.89%
❌ test_perf_openapi_large_pydantic_v2_builtin 833 ms 1,318.1 ms -36.8%
❌ test_perf_unique_items_nested_model_validation 1.5 ms 2.4 ms -36.78%
❌ test_perf_multiple_files_input 2.3 s 3.6 s -36.78%
❌ test_perf_local_reference_file_resolution 72 ms 113.5 ms -36.55%
❌ test_perf_pydantic_field_name_resolution 1.2 ms 2 ms -36.48%
❌ test_perf_mapped_reference_users 428.7 ms 671.7 ms -36.18%
... ... ... ... ...

ℹ️ Only the first 20 benchmarks are displayed. Go to the app to view all benchmarks.

Tip

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


Comparing bfmt-8 (967c182) with bfmt-7 (8ee69ef)

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. ↩

@koxudaxi
Koudai Aono (koxudaxi) merged commit 916bc9d into main Nov 10, 2026
46 of 146 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: This PR only changes the builtin formatter in _builtin_formatter.py. It replaces the old ad hoc blank-line handling for class bodies, nested import runs and the area before the import block with a port of black's EmptyLineTracker, called _BlankLinePlacer. With it, comments between statements are kept in the right block and black's blank lines go around them. The removed functions, _leading_lines_before_imports and the old _import_runs signature, are private helpers; the only other removal is the private name in the watch list in format.py. No CLI option, public Python API, template variable or supported Python version changes. The expected-output changes are whitespace only, in builtin-formatter runs that use custom templates with unusual blank lines or comments. The builtin output now matches what black produces, so several builtin and external fixtures that used to differ are now mapped as equal. That is a consistency fix, not a regression. The behaviour diff gate has no accepted or violation cells for default options. Every differing cell is crash-fix or both-fail, so default generated output is unchanged. Error handling is not changed.


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 does not normalize blank lines in class bodies Builtin formatter drops comments between class-body statements

2 participants