Skip to content

Fix aliased imports not applied to base classes and non-matching fields#2981

Merged
koxudaxi merged 1 commit intomainfrom
fix/alias-shadowed-imports-base-and-fields
Feb 7, 2026
Merged

Fix aliased imports not applied to base classes and non-matching fields#2981
koxudaxi merged 1 commit intomainfrom
fix/alias-shadowed-imports-base-and-fields

Conversation

@koxudaxi
Copy link
Copy Markdown
Owner

@koxudaxi koxudaxi commented Feb 7, 2026

Fixes: #2969

Summary by CodeRabbit

  • New Features

    • Generated example models demonstrating aliased imports: BaseItem and MyModel with optional fields and aliased type references.
  • Bug Fixes

    • Improved import aliasing so aliased imports apply consistently to field types and base-class imports, avoiding shadowing conflicts.
  • Tests

    • Added tests covering aliased-import scenarios for fields and custom base classes.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 7, 2026

📝 Walkthrough

Walkthrough

Refactors shadowed-import aliasing to collect aliased imports into a mapping and apply them in a two-pass manner to both field data types and base-class imports via a new helper, ensuring consistent alias usage across models. (46 words)

Changes

Cohort / File(s) Summary
Parser Logic
src/datamodel_code_generator/parser/base.py
Adds _alias_base_class_imports() and refactors __alias_shadowed_imports() to build a centralized aliased-imports map and apply aliases across field data types and base-class imports in a two-pass process.
Test Expected Outputs
tests/data/expected/main/openapi/shadowed_imports_base_and_fields.py, tests/data/expected/main/openapi/shadowed_imports_base_and_fields_custom_base.py
Adds new expected output files showing aliased import (Node as Node_aliased) consistently applied to base classes and all field references.
Test Cases
tests/main/openapi/test_main_openapi.py
Adds two tests: test_main_openapi_shadowed_imports_base_and_fields() and test_main_openapi_shadowed_imports_base_and_fields_custom_base() to validate consistent aliasing across fields and bases.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

breaking-change-analyzed

Poem

🐰 I hopped through imports, neat and spry,
I gave each Node a little new name—ahi!
Bases and fields in matching disguise,
No more shadowed errors — hooray, what a prize! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 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 (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main fix: aliased imports are now applied consistently to both base classes and all field types when name clashes occur.
Linked Issues check ✅ Passed The PR directly addresses issue #2969 by implementing consistent aliasing across base classes, matching fields, and non-matching fields that reference the same imported type.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the aliased imports issue: core logic in base.py, new test cases, and expected output files demonstrating the fix.

✏️ 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/alias-shadowed-imports-base-and-fields

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

github-actions Bot commented Feb 7, 2026

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Feb 7, 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/alias-shadowed-imports-base-and-fields (35bfa01) with main (365419e)

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
Copy link
Copy Markdown

codecov Bot commented Feb 7, 2026

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #2981   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           94        94           
  Lines        17780     17811   +31     
  Branches      2044      2055   +11     
=========================================
+ Hits         17780     17811   +31     
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/alias-shadowed-imports-base-and-fields branch from 96fe37d to 35bfa01 Compare February 7, 2026 06:53
@koxudaxi koxudaxi enabled auto-merge (squash) February 7, 2026 06:54
@koxudaxi koxudaxi merged commit 1d6bdee into main Feb 7, 2026
33 of 34 checks passed
@koxudaxi koxudaxi deleted the fix/alias-shadowed-imports-base-and-fields branch February 7, 2026 06:55
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Feb 7, 2026

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: This PR is a bug fix that corrects import aliasing behavior. Previously, when a field name shadowed an imported type (e.g., a field named Node using type mymodule.node.Node), only that exact field would get the aliased import. Other fields using the same type (e.g., Node2: Node) would incorrectly reference the unaliased import, causing Python name shadowing errors. Similarly, base classes using shadowed types were not being aliased. The fix ensures ALL usages of a type that needs aliasing get the aliased import consistently, including base classes. This is not a breaking change because: (1) the previous generated code was incorrect/broken and would have required manual fixes, (2) the new generated code is simply correct Python that avoids name shadowing, (3) no CLI/API changes, template changes, or default behavior changes were made.


This analysis was performed by Claude Code Action

@github-actions
Copy link
Copy Markdown
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.

Wrong parent and field type with aliased import

1 participant