Skip to content

Import every model and builtin that an annotation names where the output writes it - #5998

Merged
Koudai Aono (koxudaxi) merged 3 commits into
mainfrom
fix1-7
Nov 2, 2026
Merged

Koudai Aono (koxudaxi) merged 3 commits into
mainfrom
fix1-7

Conversation

@koxudaxi

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

Copy link
Copy Markdown
Member

Fixes: #5450
Fixes: #5465
Fixes: #5524
Fixes: #5594
Fixes: #5709
Fixes: #5826

Summary by CodeRabbit

  • Bug Fixes
    • Generated models now correctly handle fields named after Python built-ins, preserving the intended types in annotations across supported output formats.
    • Improved generated imports for schemas with collapsed root models, package-level modules, generic base classes, and references from hyphenated directories.
    • Corrected built-in type annotations in generated XML Schema models when field names overlap with built-ins.

@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between bdc4c8e and 0ee7b9837a97988e6f4c349dec135d0e51fe9c40.

Files ignored due to path filters: 7
  • docs/llms-full.txt is excluded by none and included by none
  • tests/data/jsonschema/builtin_named_fields.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/hyphenated_directory_reference/a.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/hyphenated_directory_reference/my-dir/b.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/hyphenated_directory_reference/my-dir/b_list.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/openapi/collapse_root_models_package_init.yaml is excluded by !tests/data/**/*.yaml and included by none
  • tests/data/openapi/generic_base_class_other_packages.yaml is excluded by !tests/data/**/*.yaml and included by none
Files selected for processing: 38
  • docs/architecture.md
  • src/datamodel_code_generator/parser/_passes/_import_binding.py
  • src/datamodel_code_generator/parser/_passes/cross_module.py
  • src/datamodel_code_generator/parser/_passes/imports.py
  • src/datamodel_code_generator/parser/_passes/modules.py
  • tests/checks/module_imports.py
  • tests/data/expected/main/jsonschema/main_jsonschema/builtin_named_fields[dataclasses.dataclass].py
  • tests/data/expected/main/jsonschema/main_jsonschema/builtin_named_fields[msgspec.Struct].py
  • tests/data/expected/main/jsonschema/main_jsonschema/builtin_named_fields[pydantic_v2.BaseModel].py
  • tests/data/expected/main/jsonschema/main_jsonschema/builtin_named_fields[pydantic_v2.dataclass].py
  • tests/data/expected/main/jsonschema/main_jsonschema/builtin_named_fields[typing.TypedDict].py
  • tests/data/expected/main/jsonschema/main_jsonschema/hyphenated_directory_reference[collapse-root-models]/__init__.py
  • tests/data/expected/main/jsonschema/main_jsonschema/hyphenated_directory_reference[collapse-root-models]/a.py
  • tests/data/expected/main/jsonschema/main_jsonschema/hyphenated_directory_reference[collapse-root-models]/my_dir/__init__.py
  • tests/data/expected/main/jsonschema/main_jsonschema/hyphenated_directory_reference[collapse-root-models]/my_dir/b.py
  • tests/data/expected/main/jsonschema/main_jsonschema/hyphenated_directory_reference[default]/__init__.py
  • tests/data/expected/main/jsonschema/main_jsonschema/hyphenated_directory_reference[default]/a.py
  • tests/data/expected/main/jsonschema/main_jsonschema/hyphenated_directory_reference[default]/my_dir/__init__.py
  • tests/data/expected/main/jsonschema/main_jsonschema/hyphenated_directory_reference[default]/my_dir/b.py
  • tests/data/expected/main/jsonschema/main_jsonschema/hyphenated_directory_reference[default]/my_dir/b_list.py
  • tests/data/expected/main/openapi/main_openapi/collapse_root_models_package_init/__init__.py
  • tests/data/expected/main/openapi/main_openapi/collapse_root_models_package_init/other.py
  • tests/data/expected/main/openapi/main_openapi/collapse_root_models_package_init/pkg/__init__.py
  • tests/data/expected/main/openapi/main_openapi/collapse_root_models_package_init/pkg/sub.py
  • tests/data/expected/main/openapi/main_openapi/collapse_root_models_package_init/third.py
  • tests/data/expected/main/openapi/main_openapi/generic_base_class_other_packages/__init__.py
  • tests/data/expected/main/openapi/main_openapi/generic_base_class_other_packages/a/__init__.py
  • tests/data/expected/main/openapi/main_openapi/generic_base_class_other_packages/a/b.py
  • tests/data/expected/main/openapi/main_openapi/generic_base_class_other_packages/c/__init__.py
  • tests/data/expected/main/openapi/main_openapi/generic_base_class_other_packages/c/d.py
  • tests/data/expected/main/openapi/main_openapi/generic_base_class_other_packages/top.py
  • tests/data/expected/main/xmlschema/builtin_datatypes_matrix.py
  • tests/main/jsonschema/test_main_jsonschema.py
  • tests/main/jsonschema/test_main_jsonschema.refs
  • tests/main/openapi/test_main_openapi.py
  • tests/main/openapi/test_main_openapi.refs
  • tests/main/test_payload_validation.refs
  • tests/test_yaml_fast_constructor.refs

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

Walkthrough

Import-path generation now handles collapsed references, generic base classes, and output paths for hyphenated directories. Builtin-name collision handling now considers target-version builtins. Regression tests and generated fixtures cover these cases.

Changes: Module import path generation

Layer / File(s) Summary
Import target rules and collapsed-reference call sites
docs/architecture.md, src/datamodel_code_generator/parser/_passes/_import_binding.py, src/datamodel_code_generator/parser/_passes/modules.py
Import target handling now uses written module paths and treats same-module targets consistently. Root-model collapse and dict-key imports use the updated legacy row.
Generic base-class imports
src/datamodel_code_generator/parser/_passes/_import_binding.py, src/datamodel_code_generator/parser/_passes/cross_module.py, tests/checks/module_imports.py, tests/main/openapi/*, tests/data/expected/main/openapi/main_openapi/generic_base_class_other_packages/*, tests/test_yaml_fast_constructor.refs
Generic base-class imports now use the shared import-target helper and the target module’s initializer state. Tests cover bases in other packages.
Collapsed references and directory paths
tests/main/jsonschema/test_main_jsonschema.py, tests/main/jsonschema/test_main_jsonschema.refs, tests/main/openapi/*, tests/data/expected/main/jsonschema/main_jsonschema/hyphenated_directory_reference/*, tests/data/expected/main/openapi/main_openapi/collapse_root_models_package_init/*, tests/main/test_payload_validation.refs, tests/test_yaml_fast_constructor.refs
Regression cases cover collapsed-root references from package initializers, module/class name collisions, and references to schemas in hyphenated directories.

Builtin field-name collisions

Layer / File(s) Summary
Builtin names in generated annotations
src/datamodel_code_generator/parser/_passes/imports.py, tests/main/jsonschema/test_main_jsonschema.py, tests/main/jsonschema/test_main_jsonschema.refs, tests/data/expected/main/jsonschema/main_jsonschema/builtin_named_fields*, tests/data/expected/main/xmlschema/builtin_datatypes_matrix.py
Field-name collision handling now considers builtins recognized for the target Python version. Regression tests and generated outputs cover builtin-named fields across model backends.

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

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Low · previous review 0ee7b

Custom templates combined with additional imports can resolve an annotation to the wrong type when builtin aliases collide. This is a bounded compatibility issue; otherwise no concrete merge-blocking risk was established.

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: generated output now imports every referenced model and builtin needed by annotations.
Linked Issues check Passed The PR addresses all six active linked issues. The import-binding changes apply class-versus-module collision handling and __init__ relative-depth rules to collapsed-root imports for #5450 and #5465…
Out of Scope Changes check Passed The changed source files implement the linked import-path and builtin-name collision fixes. The architecture documentation updates describe those import-path changes. The added fixtures, expected outp…
Docstring Coverage Passed Docstring coverage is 100.00% 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. Documentat…
Full details: Linked Issues check

Explanation

The PR addresses all six active linked issues. The import-binding changes apply class-versus-module collision handling and __init__ relative-depth rules to collapsed-root imports for #5450 and #5465. generic_base_class_import derives the base-class import from the actual base module for #5594. The import path logic writes hyphenated directory names through their underscore form for #5709. _bind_module_field_names now covers all target-version builtins, including set, tuple, dict, and frozenset, for #5524 and #5826. Added tests and expected outputs cover collapsed imports, package initializers, generic base classes, hyphenated directories, and builtin-name collisions.

Full details: Out of Scope Changes check

Explanation

The changed source files implement the linked import-path and builtin-name collision fixes. The architecture documentation updates describe those import-path changes. The added fixtures, expected outputs, and test registrations validate the linked scenarios. No unrelated product behavior is demonstrated.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% 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 10 functions across 31 files. (7 skipped: 5 unsupported, 2 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

@koxudaxi
Koudai Aono (koxudaxi) marked this pull request as ready for review November 2, 2026 17:15
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-02T17:17:51.688827Z 0ee7b98 Draft marked ready
ℹ️ 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

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

@codspeed

codspeed Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 49.28%

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

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

❌ 52 regressed benchmarks
⏩ 98 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_perf_false_reference_validation 138.4 ms 303.9 ms -54.46%
❌ test_perf_simple_msgspec_unset_field_rendering 267.6 ms 586.7 ms -54.38%
❌ test_perf_client_calls[async] 21.7 ms 47.4 ms -54.2%
❌ test_perf_scalar_root_collapsed_builtin 103.7 ms 225.7 ms -54.03%
❌ test_perf_client_calls[sync] 20.1 ms 42.9 ms -53.25%
❌ test_perf_load_pyproject_config[mapping-None] 182.9 µs 389.4 µs -53.03%
❌ test_perf_load_pyproject_config[config-multiple] 186.3 µs 395.8 µs -52.92%
❌ test_perf_load_pyproject_config[config-None] 177 µs 374.9 µs -52.78%
❌ test_perf_pydantic_field_name_resolution 1.3 ms 2.8 ms -52.69%
❌ test_perf_inherited_required_fields[required-derived-first] 376 ms 793.9 ms -52.63%
❌ test_perf_unique_items_runtime_scalar_validation 1.5 ms 3.2 ms -52.38%
❌ test_perf_large_models_pydantic_v2 1.9 s 4 s -52.29%
❌ test_perf_load_pyproject_config[mapping-multiple] 190.8 µs 397.5 µs -52%
❌ test_perf_local_reference_file_resolution 71.3 ms 147.3 ms -51.61%
❌ test_perf_inherited_required_fields[required-base-first] 346.4 ms 711.4 ms -51.31%
❌ test_perf_large_models_typed_dict[legacy-requiredness] 636.6 ms 1,302.5 ms -51.13%
❌ test_perf_extreme_large_schema 8.5 s 17.4 s -51.09%
❌ test_perf_duplicate_names 564.2 ms 1,149.8 ms -50.93%
❌ test_perf_stripe_style_pydantic_v2 1.2 s 2.4 s -50.8%
❌ test_perf_large_models_single_module_stdout 836 ms 1,697.1 ms -50.74%
... ... ... ... ...

ℹ️ 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 fix1-7 (c7766f7) with main (b4c2c76)

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

@codecov

codecov Bot commented Nov 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Fix comments: Fix CodeRabbit comments on this PR

Base automatically changed from fix1-6 to main November 2, 2026 17:35
…put writes it

A collapsed root type and a dict key typed by a root type import the models they name by the rule of a model's own
reference (`reference_import_target`): a package `__init__` reaches a model outside its package one level up, and a
model in a module named like it is imported from that module, not as the module. Row `legacy-collapse-import-path`
becomes `legacy-collapse-internal-module-import`: only a model of an `_internal` module keeps being named through the
imported `_internal` module, as since 0.25.9, which imports. The generated base class is imported by the same rule
from the module that writes it, not from the package of the importing module. Every import names its module by the
path the output writes it at, a `-` written as `_`. A field named like a builtin class hides the builtin from the
annotations and later defaults of its class, so each builtin class the class loads under a field's name is imported
under an alias, as `list` was.

Only output that failed to import, to evaluate its annotations or to decode changes.

Fixes: #5450
Fixes: #5465
Fixes: #5524
Fixes: #5594
Fixes: #5709
Fixes: #5826
@koxudaxi
Koudai Aono (koxudaxi) merged commit f8c7957 into main Nov 2, 2026
164 of 165 checks passed
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: This PR fixes import bugs in generated code, so every output change replaces code that previously failed to import or evaluate. First, references into hyphenated directories now import from the written package name my_dir instead of my-dir, which used to be a syntax error. Second, collapsed root types inlined into a package init now import with the correct relative dot instead of a broken from . import third. Third, a collapsed array whose class shares its module name now imports the class rather than the module. Fourth, the generated base class from --use-generic-base-class (opt-in) is now imported from its real module in other packages instead of a non-importable from .d import BaseModel. Fifth, the earlier aliasing of a builtin hidden by a same-named field, which only covered list, now also covers set, dict, tuple, str, int and similar names through from builtins import X as X_aliased. Previously those annotations raised a TypeError or failed get_type_hints. The behaviour diff gate agrees: the cells tied to this PR (builtin_named_fields, hyphenated_directory_reference, collapse_root_models_package_init, x_python_type_builtin_dict_collision) are all classed crash-fix or no-behaviour. The only accepted cells concern integer multipleOf and exclusive bounds past 2 to the 53, which this diff does not touch, so they come from other changes since the last release. The removed or renamed symbols (_generic_base_class_module, ReferenceImportTarget.row, the legacy-collapse-import-path literal, which became legacy-collapse-internal-module-import, and the signature of _bind_module_field_names) all live in private parser _passes modules, so no public API changes. No CLI options, defaults, templates, Python version support or error handling changed.


This analysis was produced by the release draft workflow

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