Skip to content

Fix incorrect relative imports with --use-exact-imports and --collapse-root-models#2996

Merged
koxudaxi merged 5 commits intomainfrom
fix/exact-imports-collapse-root-models-collision
Feb 14, 2026
Merged

Fix incorrect relative imports with --use-exact-imports and --collapse-root-models#2996
koxudaxi merged 5 commits intomainfrom
fix/exact-imports-collapse-root-models-collision

Conversation

@koxudaxi
Copy link
Owner

@koxudaxi koxudaxi commented Feb 14, 2026

Fixes: #2979

Summary by CodeRabbit

  • New Features

    • Import resolution now supports an explicit "exact imports" mode when collapsing root models, improving import accuracy and aliasing.
  • Generated Output

    • Generated model files and package initializers updated to reflect exact-imports behavior; ensures a top-level init.py when outputs span multiple top-level directories.
  • Tests

    • Added test coverage for exact-imports combined with root-model collapse and name-collision scenarios.

@coderabbitai
Copy link

coderabbitai bot commented Feb 14, 2026

📝 Walkthrough

Walkthrough

Apply exact import path computation when imports.use_exact is enabled for root-type and non-BaseClass imports, and create a top-level __init__.py when multiple top-level directories are produced during module finalization.

Changes

Cohort / File(s) Summary
Parser core
src/datamodel_code_generator/parser/base.py
When imports.use_exact is true, use exact_import to compute exact from_/import_ pairs in __collapse_root_models and __change_from_import; add guard to emit a top-level __init__.py if multiple top-level dirs exist.
Generated fixtures (expected)
tests/data/expected/main/jsonschema/exact_imports_collapse_root_models/__init__.py, tests/data/expected/main/jsonschema/exact_imports_collapse_root_models/data/__init__.py, tests/data/expected/main/jsonschema/exact_imports_collapse_root_models/data/ReflectionSetData.py, tests/data/expected/main/jsonschema/exact_imports_collapse_root_models/datatypes/__init__.py, tests/data/expected/main/jsonschema/exact_imports_collapse_root_models/datatypes/FooStats.py, tests/data/expected/main/jsonschema/exact_imports_collapse_root_models/datatypes/BarStats.py
Add expected generated model modules and package __init__.py files reflecting exact-import paths and collapsed root-model outputs.
Tests
tests/main/jsonschema/test_main_jsonschema.py
Add test_main_exact_imports_collapse_root_models_module_class_collision to verify generation with --use-exact-imports + --collapse-root-models (guarded with PYDANTIC_V2_SKIP).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

breaking-change-analyzed

Poem

🐰 Hopping through code with a twitch and a wink,
Exact paths now chosen — imports no longer stink.
Roots collapsed tidy, top-level files in sight,
I nibble through collisions and hop off tonight. 🥕

🚥 Pre-merge checks | ✅ 5 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately describes the main fix: addressing incorrect relative imports when using --use-exact-imports with --collapse-root-models flags.
Linked Issues check ✅ Passed The PR directly addresses issue #2979 by fixing the generation of correct relative import paths (from ..datatypes.FooStats import FooStats) instead of duplicated/incorrect imports when using --use-exact-imports and --collapse-root-models together.
Out of Scope Changes check ✅ Passed All changes are in scope: core parser fix in base.py, expected test output files for the new test case, and a new integration test verifying the fix for the exact collision scenario.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into main

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/exact-imports-collapse-root-models-collision

No actionable comments were generated in the recent review. 🎉


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
Contributor

github-actions bot commented Feb 14, 2026

📚 Docs Preview: https://pr-2996.datamodel-code-generator.pages.dev

@koxudaxi koxudaxi force-pushed the fix/exact-imports-collapse-root-models-collision branch from e340619 to 3efdf81 Compare February 14, 2026 06:20
@codecov
Copy link

codecov bot commented Feb 14, 2026

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #2996   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           94        94           
  Lines        18120     18130   +10     
  Branches      2096      2099    +3     
=========================================
+ Hits         18120     18130   +10     
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 force-pushed the fix/exact-imports-collapse-root-models-collision branch from 3efdf81 to c742151 Compare February 14, 2026 15:09
@codspeed-hq
Copy link

codspeed-hq bot commented Feb 14, 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/exact-imports-collapse-root-models-collision (ea6e8dd) with main (34b7d29)

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 koxudaxi merged commit 2ea6244 into main Feb 14, 2026
38 checks passed
@koxudaxi koxudaxi deleted the fix/exact-imports-collapse-root-models-collision branch February 14, 2026 16:11
@github-actions
Copy link
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: This PR is a bug fix that corrects two issues: (1) When using --use-exact-imports with --collapse-root-models, relative imports were not being transformed to exact imports, producing incorrect/broken code. The fix applies exact_import() in this code path. (2) When output spans multiple top-level directories, a root __init__.py is now generated to ensure a valid Python package structure. Both changes fix incorrect behavior rather than modifying correct behavior, so they are not breaking changes. Users who were encountering the bug will see different (working) output, but this is the expected outcome of a bug fix.


This analysis was performed by Claude Code Action

@github-actions
Copy link
Contributor

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

Relative imports from parallel directories incorrect

1 participant