Skip to content

Fix exact imports for reused tree-scope models#3042

Merged
koxudaxi merged 1 commit intomainfrom
fix/issue-3037-reuse-scope-tree-exact-imports
Mar 10, 2026
Merged

Fix exact imports for reused tree-scope models#3042
koxudaxi merged 1 commit intomainfrom
fix/issue-3037-reuse-scope-tree-exact-imports

Conversation

@koxudaxi
Copy link
Copy Markdown
Owner

@koxudaxi koxudaxi commented Mar 10, 2026

Fixes: #3037

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced inherited model reference handling to ensure child references are properly migrated during code generation, improving accuracy when reusing models across schemas.
  • Tests

    • Expanded test coverage validating model reuse functionality when combined with exact imports. Tests now ensure proper schema generation across multiple related definitions and verify compatibility with various configuration options.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 10, 2026

📝 Walkthrough

Walkthrough

A fix to the reuse-model generation flow that immediately updates child references in models after creating an inherited model, ensuring proper reference migration in the parser. Includes corresponding test data validating the combination of --reuse-scope=tree with --use-exact-imports for Pydantic v2.

Changes

Cohort / File(s) Summary
Core Parser Logic
src/datamodel_code_generator/parser/base.py
Adds immediate call to replace_children_in_models() after creating a reused/inherited model to migrate child references to the new inherited model in the surrounding models list.
Test Data - Expected Outputs
tests/data/expected/main/jsonschema/reuse_scope_tree_exact_imports/__init__.py, tests/data/expected/main/jsonschema/reuse_scope_tree_exact_imports/schema_a.py, tests/data/expected/main/jsonschema/reuse_scope_tree_exact_imports/schema_b.py, tests/data/expected/main/jsonschema/reuse_scope_tree_exact_imports/shared.py
New generated data models validating reuse-scope=tree with exact imports; includes SharedModel class with optional id and name fields, and two Model classes that reference SharedModel.
Test Coverage
tests/main/jsonschema/test_main_jsonschema.py
Adds new test function validating the combination of --reuse-scope=tree with --use-exact-imports flags for Pydantic v2.BaseModel output.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested labels

breaking-change-analyzed

Poem

🐰 A model inherits with perfect grace,
Its children now gather in the right place,
No more lost references stuck in the tree,
The reuse-scope fixes what it should be! 🌳

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main fix: addressing exact imports for tree-scope reused models, which directly corresponds to the core issue being resolved.
Linked Issues check ✅ Passed The PR implements the necessary fix by updating model references and ensuring reused models are imported normally rather than under TYPE_CHECKING, matching the expected behavior from issue #3037.
Out of Scope Changes check ✅ Passed All changes are in-scope: the core fix to base.py handles model child reference replacement, and the test additions validate the fix for the exact-imports with tree-scope reuse combination.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/issue-3037-reuse-scope-tree-exact-imports

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Copy Markdown
Contributor

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Mar 10, 2026

Merging this PR will not alter performance

⚠️ Unknown Walltime execution environment detected

Using the Walltime instrument on standard Hosted Runners will lead to inconsistent data.

For the most accurate results, we recommend using CodSpeed Macro Runners: bare-metal machines fine-tuned for performance measurement consistency.

✅ 11 untouched benchmarks
⏩ 98 skipped benchmarks1


Comparing fix/issue-3037-reuse-scope-tree-exact-imports (0628d8b) with main (8c4bfd1)

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.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
tests/main/jsonschema/test_main_jsonschema.py (1)

5716-5730: Execute the generated package in this exact-imports regression.

Line 5716 only snapshots the generated files. Since #3037 is an import-time failure, I’d make this test assert runtime importability too with force_exec_validation=True (or an explicit import step).

Suggested change
     run_main_and_assert(
         input_path=JSON_SCHEMA_DATA_PATH / "reuse_scope_tree",
         output_path=output_dir,
         expected_directory=EXPECTED_JSON_SCHEMA_PATH / "reuse_scope_tree_exact_imports",
         input_file_type="jsonschema",
         extra_args=[
             "--output-model-type",
             "pydantic_v2.BaseModel",
             "--reuse-model",
             "--reuse-scope",
             "tree",
             "--use-exact-imports",
             "--disable-timestamp",
         ],
+        force_exec_validation=True,
     )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/main/jsonschema/test_main_jsonschema.py` around lines 5716 - 5730, The
test currently only snapshots generated files via run_main_and_assert for the
"reuse_scope_tree" case but doesn't validate runtime importability; adjust the
call to run_main_and_assert (the helper used in this test) to enable execution
validation by adding force_exec_validation=True so the generated package is
actually imported/executed (or alternatively add an explicit import step after
generation) to catch the import-time failure seen in issue `#3037`.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tests/main/jsonschema/test_main_jsonschema.py`:
- Around line 5716-5730: The test currently only snapshots generated files via
run_main_and_assert for the "reuse_scope_tree" case but doesn't validate runtime
importability; adjust the call to run_main_and_assert (the helper used in this
test) to enable execution validation by adding force_exec_validation=True so the
generated package is actually imported/executed (or alternatively add an
explicit import step after generation) to catch the import-time failure seen in
issue `#3037`.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d5aa141e-a93f-419a-b044-abd03aea15bd

📥 Commits

Reviewing files that changed from the base of the PR and between 8c4bfd1 and 0628d8b.

📒 Files selected for processing (6)
  • src/datamodel_code_generator/parser/base.py
  • tests/data/expected/main/jsonschema/reuse_scope_tree_exact_imports/__init__.py
  • tests/data/expected/main/jsonschema/reuse_scope_tree_exact_imports/schema_a.py
  • tests/data/expected/main/jsonschema/reuse_scope_tree_exact_imports/schema_b.py
  • tests/data/expected/main/jsonschema/reuse_scope_tree_exact_imports/shared.py
  • tests/main/jsonschema/test_main_jsonschema.py

@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 10, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (8c4bfd1) to head (0628d8b).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #3042   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           85        85           
  Lines        17688     17692    +4     
  Branches      2068      2068           
=========================================
+ Hits         17688     17692    +4     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@koxudaxi koxudaxi merged commit 95daa4e into main Mar 10, 2026
38 checks passed
@koxudaxi koxudaxi deleted the fix/issue-3037-reuse-scope-tree-exact-imports branch March 10, 2026 02:18
@github-actions
Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: This PR is a bug fix that corrects incorrect code generation when using --use-exact-imports with --reuse-scope=tree. The change adds calls to replace_children_in_models() to ensure that when models are reused (creating inherited aliases), other models that reference the original model get their references properly updated to point to the new inherited model. Bug fixes that correct broken behavior are not breaking changes - they are corrections that make the tool produce valid output. No API, CLI, template, default behavior, or Python version changes were made.


This analysis was performed by Claude Code Action

@github-actions
Copy link
Copy Markdown
Contributor

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

Reuse model fails and imports new class under type_checking in json schema to pydantic v2 conversion

1 participant