Skip to content

Import a mapped class only in the modules that use it - #6796

Merged
Koudai Aono (koxudaxi) merged 1 commit into
release-draft-jq-limitfrom
mapped-import-per-module
Nov 13, 2026
Merged

Koudai Aono (koxudaxi) merged 1 commit into
release-draft-jq-limitfrom
mapped-import-per-module

Conversation

@koxudaxi

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

Copy link
Copy Markdown
Member

Fixes: #6787

Summary by CodeRabbit

  • Bug Fixes
    • Corrected generated imports for externally mapped types and custom Python imports. Shared imports are retained where needed, but written only in modules that use the referenced type, reducing unnecessary imports and avoiding conflicts with locally defined models.
  • Documentation
    • Clarified how shared imports are handled across generated modules.

@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The import plan now distinguishes shared import names from imports rendered in each module. Module and empty package-initializer generation receive shared import text. Tests cover external reference mappings across generated modules.

Changes: Shared import rendering

Layer / File(s) Summary
Classify shared imports
src/datamodel_code_generator/parser/_imports_plan.py, docs/architecture.md
The import plan identifies external-ref-mapping and x-python-import entries as shared imports. Documentation states that a module writes an import when its model names the class.
Pass shared imports to output generation
src/datamodel_code_generator/parser/_passes/imports.py, src/datamodel_code_generator/parser/base.py, src/datamodel_code_generator/_target_binding.py
Module rendering passes shared import text to module and empty package-initializer generation. The base and target-binding methods accept and forward that text.
Verify generated imports
tests/main/jsonschema/test_main_jsonschema.py, tests/main/jsonschema/test_main_jsonschema.refs, tests/main/test_payload_validation.refs, tests/data/expected/main/jsonschema/main_jsonschema/*
Tests and expected outputs cover external-reference mappings across modules, payload validation, and removal of an unused OrderedDict import.

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

Change: Bug fix · Severity of issue fixed: Medium

Possibly related PRs

Merge Risk: Minimal · up to f72e7

Mapped class imports are now written only in modules that use them, as issue #6787 requests, and no actionable merge-blocking risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title states the main change: a mapped class is now imported only in the modules that use it. The raw summary shows the shared-import handling in the parser and the tests that check the mapped imp…
Linked Issues check Passed [#6787] Objective: with --external-ref-mapping and directory input, only the module that uses the mapped $ref class (out/order.py, Customer) imports it. Other modules (out/product.py) import only pyda…
Out of Scope Changes check Passed Changes in the current PR (base 362cc90 to head f72e7fa) relate to the #6787 fix:
- Core changes in parser/base.py, parser/_imports_plan.py, parser/_passes/imports.py, and _target_binding.py pass shar…
Full details: Title check

Explanation

The title states the main change: a mapped class is now imported only in the modules that use it. The raw summary shows the shared-import handling in the parser and the tests that check the mapped import is written only where its model uses the type. This matches the linked issue #6787, which asks that only the module using the mapped class import it.

Full details: Linked Issues check

Explanation

[#6787] Objective: with --external-ref-mapping and directory input, only the module that uses the mapped $ref class (out/order.py, Customer) imports it. Other modules (out/product.py) import only pydantic.BaseModel.

Evidence from the PR summary and attested file summaries:

  • src/datamodel_code_generator/parser/_imports_plan.py: the module docs and _without_unrendered now treat Added entries from the external-ref-mapping and x-python-import shared-import passes as rendering no imports. The name is kept in shared imports, but only the module whose model names the type writes the import.
  • src/datamodel_code_generator/parser/base.py: _generate_module_output and _generate_empty_init_exports take shared import text instead of rendering self.imports directly.
  • src/datamodel_code_generator/parser/_passes/imports.py: render_modules renders shared imports once and passes them to module-output and empty-init generation, including the --treat-dot-as-module path.
  • Expected snapshot tests/data/expected/main/jsonschema/main_jsonschema/external_ref_mapping_modules/product.py is added with a Product model and no mapped import. order.py imports the mapped types.
  • tests/main/jsonschema/test_main_jsonschema.py adds a test for external-ref-mapping imports and updates the shared-import collision test description.

Stack note: PR #6793 is uncertain and has no current review evidence. PR #6794 is reviewed and only changes .github/workflows/release-draft.yaml, which does not touch the import path. The current PR diff, taken from base 362cc90, contains the code changes that implement this objective. The objective is therefore Addressed by PR #6796 alone. Limit: the source was not read directly. The conclusion rests on the attested summaries and the expected-output fixtures.

Full details: Out of Scope Changes check

Explanation

Changes in the current PR (base 362cc90 to head f72e7fa) relate to the #6787 fix:

  • Core changes in parser/base.py, parser/_imports_plan.py, parser/_passes/imports.py, and _target_binding.py pass shared import text through module and empty-init generation. This is the mechanism for the fix.
  • docs/architecture.md documents the shared-import behavior for external-ref-mapping and x-python-import. This is documentation of the changed behavior.
  • Expected output changes in shared_import_named_like_module_and_model (removed collections.OrderedDict import, unused because the local OrderedDict model shadows it) follow from the same rule: shared imports render only in modules that use them.
  • New fixture expected outputs (external_ref_mapping_modules/init.py, order.py, product.py) and the test additions in test_main_jsonschema.py and test_main_jsonschema.refs support the new test case.
  • test_payload_validation.refs adds the new product.json fixture to payload validation cases. This is test coverage for the new fixture. It is a minor, supporting addition and does not change product behavior.

No change was found that is unrelated to #6787. Ignored test input files were not inspected. Their exclusion does not change this result.

Finishing Touches

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 362cc90 and f72e7fa.

Files ignored due to path filters: 6

  • docs/llms-full.txt is excluded by none and included by none
  • tests/data/expected/main/generation_platform/client/bindings/session-alias-forms.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/generation_platform/client/bindings/session-nullable-root-alias.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/generation_platform/client/bindings/type-projection.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/jsonschema/external_ref_mapping_modules/order.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/external_ref_mapping_modules/product.json is excluded by !tests/data/**/*.json and included by none
Files selected for processing: 13

  • docs/architecture.md
  • src/datamodel_code_generator/_target_binding.py
  • src/datamodel_code_generator/parser/_imports_plan.py
  • src/datamodel_code_generator/parser/_passes/imports.py
  • src/datamodel_code_generator/parser/base.py
  • tests/data/expected/main/jsonschema/main_jsonschema/external_ref_mapping_modules/__init__.py
  • tests/data/expected/main/jsonschema/main_jsonschema/external_ref_mapping_modules/order.py
  • tests/data/expected/main/jsonschema/main_jsonschema/external_ref_mapping_modules/product.py
  • tests/data/expected/main/jsonschema/main_jsonschema/shared_import_named_like_module_and_model/IPv4Address.py
  • tests/data/expected/main/jsonschema/main_jsonschema/shared_import_named_like_module_and_model/__init__.py
  • tests/main/jsonschema/test_main_jsonschema.py
  • tests/main/jsonschema/test_main_jsonschema.refs
  • tests/main/test_payload_validation.refs
Files with no reviewable changes: 2

  • tests/data/expected/main/jsonschema/main_jsonschema/shared_import_named_like_module_and_model/IPv4Address.py
  • tests/data/expected/main/jsonschema/main_jsonschema/shared_import_named_like_module_and_model/init.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.

@koxudaxi
Koudai Aono (koxudaxi) marked this pull request as ready for review November 13, 2026 07:28
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 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-13T07:31:05.921658Z f72e7fa 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

Copy link
Copy Markdown
Contributor

@codspeed

codspeed Bot commented Nov 13, 2026

Copy link
Copy Markdown

Merging this PR will degrade performance by 15%

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

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

❌ 26 regressed benchmarks
✅ 27 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_msgspec_unset_field_rendering 330.7 ms 471.3 ms -29.83%
❌ test_perf_client_calls[sync] 25.4 ms 31.6 ms -19.41%
❌ test_perf_scalar_root_collapsed_builtin 145.5 ms 179.9 ms -19.1%
❌ test_perf_client_calls[async] 28.7 ms 35.1 ms -18.19%
❌ test_perf_large_models_pydantic_v2_builtin 1.1 s 1.3 s -18.08%
❌ test_perf_large_models_single_module_stdout 1.3 s 1.6 s -17.93%
❌ test_perf_large_models_dataclass_builtin 1.1 s 1.3 s -17.44%
❌ test_perf_large_models_typed_dict[total-false-requiredness] 927.3 ms 1,119 ms -17.13%
❌ test_perf_large_models_pydantic_v2_noformat 1.1 s 1.3 s -16.16%
❌ test_perf_large_models_pydantic_v2_builtin_double_quotes 1.2 s 1.4 s -15.97%
❌ test_perf_large_models_msgspec 1.6 s 1.9 s -15.46%
❌ test_perf_large_models_typed_dict[legacy-requiredness] 945.1 ms 1,115 ms -15.24%
❌ test_perf_ordinary_array_constraint_generation 1.7 s 2 s -14.32%
❌ test_perf_inherited_required_fields[required-base-first] 572.6 ms 666.3 ms -14.06%
❌ test_perf_unique_items_runtime_nested_object_validation 5.5 ms 6.4 ms -13.83%
❌ test_perf_large_models_pydantic_v2 2.7 s 3.1 s -12.99%
❌ test_perf_duplicate_names 792 ms 908.5 ms -12.83%
❌ test_perf_aws_style_openapi_pydantic_v2 1.8 s 2 s -12.5%
❌ test_perf_local_reference_file_resolution 107.8 ms 122.3 ms -11.87%
❌ test_perf_unique_items_permuted_object_validation 53.5 ms 60.6 ms -11.78%
... ... ... ... ...

ℹ️ 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 mapped-import-per-module (f72e7fa) with release-draft-jq-limit (362cc90)

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 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@koxudaxi
Koudai Aono (koxudaxi) merged commit e426c95 into main Nov 13, 2026
117 of 118 checks passed
@koxudaxi
Koudai Aono (koxudaxi) deleted the mapped-import-per-module branch November 13, 2026 19:35
@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: The PR changes how shared imports are written. The Python type that an --external-ref-mapping ref or an x-python-import names still keeps its name in every module, so model naming does not change. But only a module whose model actually names the type now writes the import. Before, every module of a multi-module output wrote it, including modules that never use it. That made unrelated modules fail with ModuleNotFoundError when the external package was missing. The behaviour diff gate marks the new external_ref_mapping_modules input as a crash-fix. The x-python-import cells are marked no-behaviour or both-fail. The only accepted cells concern regex patterns that hold single quotes. This diff touches no pattern code, so those cells come from other changes since 0.95.0. In the expected outputs, the only changes are unused import lines removed from modules that do not reference the mapped class, and binding-test line offsets shifted by one because the import block layout changed. No generated model names, types or fields change. The internal signatures of _generate_module_output and _generate_empty_init_exports gained a shared_imports_str parameter, but these are private methods, not public API. No CLI options, defaults, template variables, Python version support or error reporting change. This is a bug fix and not a breaking change.


This analysis was produced by the release draft workflow

@github-actions

Copy link
Copy Markdown
Contributor

🎉 Released in 0.96.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.

--external-ref-mapping imports the mapped class into every output module

1 participant