Skip to content

Rename a model named like an additional import that a type of its module writes by that name - #6041

Merged
Koudai Aono (koxudaxi) merged 1 commit into
fix1-30from
fix1-31
Nov 3, 2026
Merged

Koudai Aono (koxudaxi) merged 1 commit into
fix1-30from
fix1-31

Conversation

@koxudaxi

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

Copy link
Copy Markdown
Member

Fixes: #6010

Summary by CodeRabbit

  • Bug Fixes
    • Fixed generated model naming when a model shares a name with an additional import. Models are now renamed when needed to preserve references to imported types, including types expressed as text.
    • Improved generated output across dataclass and Pydantic models, including cases where the colliding model is used or unused.

@coderabbitai

coderabbitai Bot commented Nov 3, 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
Walkthrough

The import-name pass now uses model type information to detect collisions between shared imports and generated model names. It renames a colliding model when a type writes the import’s name. Regression tests cover dataclass and Pydantic output, including payload validation.

Changes: Shared import name collision handling

Layer / File(s) Summary
Type-aware collision detection
src/datamodel_code_generator/parser/_passes/imports.py, scripts/pass_decls.py, docs/architecture.md
The pass reads FIELD_TYPES and collects names from unreferenced Python type expressions and string types. When a non-__future__ shared import matches a local model name written by a type, the pass renames the model. Existing local-import checks and the Literal alias exception remain.
Regression coverage for generated output and payloads
tests/main/jsonschema/test_main_jsonschema.py, tests/data/expected/main/jsonschema/main_jsonschema/additional_import_named_like_model*, tests/main/jsonschema/test_main_jsonschema.refs, tests/main/test_payload_validation.refs
Tests cover used and unused name collisions for dataclass and Pydantic output. Expected generated code and payload results are added for these cases.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Low

Possibly related issues

Possibly related PRs

Merge Risk: Moderate · previous review c035c

Generated models can receive unnecessary names or shadow another imported type, causing annotations to resolve incorrectly. Correct name collection and reserve shared bindings during renaming before merging.

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 states the primary behavior change: a model is renamed when a type in its module writes the name of an additional import. The raw summary confirms the change in scripts/pass_decls.py and src…
Linked Issues check Passed For [#6010], change_imported_model_name now reads FIELD_TYPES and renames a local model when a shared, non-__future__ import name is written as text in a model type. The change preserves the imp…
Out of Scope Changes check Passed The changes stay within [#6010]. The pass-table declarations and architecture documentation describe the new input and behavior. The generated snapshots, fixtures, and regression tests verify the impo…
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: Title check

Explanation

The title states the primary behavior change: a model is renamed when a type in its module writes the name of an additional import. The raw summary confirms the change in scripts/pass_decls.py and src/datamodel_code_generator/parser/_passes/imports.py, which extend change_imported_model_name to consider shared imports whose names appear as text in model types. The added regression tests for the colliding names support this. The title matches the PR objectives, which describe the same narrowed rename behavior from issue 6010.

Full details: Linked Issues check

Explanation

For [#6010], change_imported_model_name now reads FIELD_TYPES and renames a local model when a shared, non-__future__ import name is written as text in a model type. The change preserves the imported IPv4Address binding for the generated IPv4Address1 model. Regression coverage includes Pydantic v2 and dataclass output, plus used and unused model cases.

Full details: Out of Scope Changes check

Explanation

The changes stay within [#6010]. The pass-table declarations and architecture documentation describe the new input and behavior. The generated snapshots, fixtures, and regression tests verify the import-name collision behavior. No unrelated product behavior is shown.

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 2 functions across 6 files. (4 skipped: 3 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

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.
Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 0123521900c366f032be500c477c1c9ff9e66623 and c035ce3904ac563fa92276c8b1c8ce1f1aec9762.

Files ignored due to path filters: 5
  • docs/llms-full.txt is excluded by none and included by none
  • tests/data/expected/main/jsonschema/main_jsonschema/additional_import_named_like_model[unused-dataclasses.dataclass].payloads.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/jsonschema/main_jsonschema/additional_import_named_like_model[written-dataclasses.dataclass].payloads.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/jsonschema/additional_import_named_like_model.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/additional_import_named_like_unused_model.json is excluded by !tests/data/**/*.json and included by none
Files selected for processing: 10
  • docs/architecture.md
  • scripts/pass_decls.py
  • src/datamodel_code_generator/parser/_passes/imports.py
  • tests/data/expected/main/jsonschema/main_jsonschema/additional_import_named_like_model[unused-dataclasses.dataclass].py
  • tests/data/expected/main/jsonschema/main_jsonschema/additional_import_named_like_model[unused-pydantic_v2.BaseModel].py
  • tests/data/expected/main/jsonschema/main_jsonschema/additional_import_named_like_model[written-dataclasses.dataclass].py
  • tests/data/expected/main/jsonschema/main_jsonschema/additional_import_named_like_model[written-pydantic_v2.BaseModel].py
  • tests/main/jsonschema/test_main_jsonschema.py
  • tests/main/jsonschema/test_main_jsonschema.refs
  • tests/main/test_payload_validation.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.

@koxudaxi
Koudai Aono (koxudaxi) marked this pull request as ready for review November 3, 2026 03:16
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 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-03T03:18:29.257249Z c035ce3 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 3, 2026

Copy link
Copy Markdown
Contributor

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c035ce3904

ℹ️ About Codex in GitHub

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

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "Codex (@codex) review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "Codex (@codex) address that feedback".

@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

@codspeed

codspeed Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 14.03%

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

❌ 13 regressed benchmarks
✅ 39 untouched benchmarks
⏩ 98 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_perf_simple_pydantic_v2_field_construction 10.7 ms 14.7 ms -26.98%
❌ test_perf_load_yaml_openapi_large 33 ms 42.5 ms -22.33%
❌ test_perf_inherited_required_fields[required-base-first] 647.1 ms 756.4 ms -14.45%
❌ test_perf_target_render[client-small] 32.1 ms 37.3 ms -14.03%
❌ test_perf_target_render[fastapi-small] 20.6 ms 23.7 ms -12.96%
❌ test_perf_ordinary_array_constraint_generation 2 s 2.3 s -12.46%
❌ test_perf_inherited_required_fields[required-derived-first] 733.1 ms 837.5 ms -12.46%
❌ test_perf_openapi_large_pydantic_v2_builtin 1.3 s 1.5 s -11.73%
❌ test_perf_target_render[fastapi-large] 6.5 s 7.3 s -11.31%
❌ test_perf_large_models_pydantic_v2_builtin 1.4 s 1.5 s -10.98%
❌ test_perf_large_models_typed_dict[legacy-requiredness] 1.2 s 1.4 s -10.41%
❌ test_perf_large_models_pydantic_v2_builtin_double_quotes 1.4 s 1.6 s -10.18%
❌ test_perf_large_models_typed_dict[total-false-requiredness] 1.2 s 1.4 s -10.16%

Tip

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


Comparing fix1-31 (b1f4347) with fix1-30 (e64fd22)

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

…ule writes by that name

`--additional-imports ipaddress.IPv4Address` is written by every module. A model of that name hid the import from the
types of its module that write the name as text (`x-python-type: IPv4Address`), which then named the model itself.
The model is renamed, as it is for an import of its own module (`change_imported_model_name`); a model whose module
writes no such name keeps its own.

Output changes only where a type of the module writes the name of an additional import that a model of the module
takes.

Fixes: #6010
Koudai Aono (koxudaxi) added a commit that referenced this pull request Nov 3, 2026
Hyphenated directory (#6039). A directory is read as importable by its name once its `-` is `_`, as the output writes it
(`written_name`): `café-models` is written to `café_models/` and imported by that name, as the files of 0.88.0 were
written, where the check came before the `-` was replaced and the directory was sanitized as a file's name is
(`caf__models`), so it moved and two directories of the same length (`café-models`, `cafè-models`) shared one package. The
import of such a directory was a syntax error up to 0.88.0 (`from .café-models import a`), so only output that failed to
import changes.

Names an additional import binds (#6041). A type of a module that writes a dotted name writes the first name of it where
the module's names are read (`ipaddress.IPv4Address` binds `ipaddress`), not the last one. The check of the imports every
module writes that a model of the module shadows reads that first name (`iter_python_type_expr_head_names`), so a model
named like the last name of a qualified runtime symbol (`x-python-import` `symbols`) keeps its name, as in 0.88.0. The
name a model or an import takes anew where a shared import binds the name it had skips the names the shared imports bind
(`shared_import_bindings`), so `IPv4Address1` is not given to a model where `mymod.IPv4Address1` is imported by every
module, nor `Status_1` or `list_1` to the import a package names anew.

Enum member defaults (#6040). `set_default_enum_member` writes a member by the expression its type names the enum by when
it runs, so a default kept naming the import that the passes of the imports named anew afterwards (`Status` for
`Status as Status_1`, `list.Pop` for `list_1.Pop`) and the generated module failed to import. The two passes that name an
import anew write the new expression into the members of the defaults that use it (`name_enum_member`, a store mutation
with its row in the fact table).

Item counts (#6037). The item counts that `contains` and boolean `items` imply belong to a field whose schema admits an
array (it declares no type, or an array is one of them) as well as whose type can hold one: a string typed
`datetime.date` and an object with array values (`{"type": "object", "additionalProperties": {"type": "array"}}`) took
`min_length` from them, which raised `Unable to apply constraint` for a date and rejected the maps with fewer keys.
@koxudaxi
Koudai Aono (koxudaxi) merged commit 251aa6d into main Nov 3, 2026
29 of 30 checks passed
@koxudaxi
Koudai Aono (koxudaxi) deleted the fix1-31 branch November 3, 2026 07:53
Koudai Aono (koxudaxi) added a commit that referenced this pull request Nov 3, 2026
…, so a run without models does not load it (#6043)

* Import the type expression reader of the model renames where they run, so a run without models does not load it

* Fix the unresolved review findings of #6037, #6039, #6040 and #6041

Hyphenated directory (#6039). A directory is read as importable by its name once its `-` is `_`, as the output writes it
(`written_name`): `café-models` is written to `café_models/` and imported by that name, as the files of 0.88.0 were
written, where the check came before the `-` was replaced and the directory was sanitized as a file's name is
(`caf__models`), so it moved and two directories of the same length (`café-models`, `cafè-models`) shared one package. The
import of such a directory was a syntax error up to 0.88.0 (`from .café-models import a`), so only output that failed to
import changes.

Names an additional import binds (#6041). A type of a module that writes a dotted name writes the first name of it where
the module's names are read (`ipaddress.IPv4Address` binds `ipaddress`), not the last one. The check of the imports every
module writes that a model of the module shadows reads that first name (`iter_python_type_expr_head_names`), so a model
named like the last name of a qualified runtime symbol (`x-python-import` `symbols`) keeps its name, as in 0.88.0. The
name a model or an import takes anew where a shared import binds the name it had skips the names the shared imports bind
(`shared_import_bindings`), so `IPv4Address1` is not given to a model where `mymod.IPv4Address1` is imported by every
module, nor `Status_1` or `list_1` to the import a package names anew.

Enum member defaults (#6040). `set_default_enum_member` writes a member by the expression its type names the enum by when
it runs, so a default kept naming the import that the passes of the imports named anew afterwards (`Status` for
`Status as Status_1`, `list.Pop` for `list_1.Pop`) and the generated module failed to import. The two passes that name an
import anew write the new expression into the members of the defaults that use it (`name_enum_member`, a store mutation
with its row in the fact table).

Item counts (#6037). The item counts that `contains` and boolean `items` imply belong to a field whose schema admits an
array (it declares no type, or an array is one of them) as well as whose type can hold one: a string typed
`datetime.date` and an object with array values (`{"type": "object", "additionalProperties": {"type": "array"}}`) took
`min_length` from them, which raised `Unable to apply constraint` for a date and rejected the maps with fewer keys.

* Provide the module the additional imports of the renamed-import test name, so the output imports on Python 3.10
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: The diff only extends the change_imported_model_name pass so that a model whose class name equals a binding from the opt-in additional-imports option is renamed when a type of its module writes that name as text, for example through x-python-type, and adds docs, pass declaration metadata and tests for it. Previously such output was incorrect because the local class shadowed the import and the field type resolved to the model itself, so a field like host rejected valid IP addresses; now the model becomes IPv4Address1 and the field uses the imported type, while models whose module does not write the name keep their names. This is a bug fix for an opt-in option combination and does not change default output. The accepted cells of the behaviour diff gate concern constraint handling and integer precision, which this diff does not touch, so they are not attributable to this PR. No CLI options, API parameters, templates, Python version support or error handling were removed or changed; the deleted lines are only docstrings, a pass summary, pass read metadata and a coverage pragma.


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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A model class named like an additional import hides the import from its own fields

1 participant