Skip to content

fix: use TypeAdapter for union dict defaults in type aliases and inline unions#3041

Closed
koxudaxi wants to merge 1 commit into
mainfrom
fix/type-alias-union-default-dict
Closed

fix: use TypeAdapter for union dict defaults in type aliases and inline unions#3041
koxudaxi wants to merge 1 commit into
mainfrom
fix/type-alias-union-default-dict

Conversation

@koxudaxi

@koxudaxi koxudaxi commented Mar 9, 2026

Copy link
Copy Markdown
Owner

Fixes: #3034
Fixes: #3035

Summary by CodeRabbit

  • New Features

    • Enhanced default value handling for union types in Pydantic v2 models, enabling proper validation of default objects for discriminated unions and type aliases.
  • Tests

    • Added test coverage for union defaults with type aliases and multi-model unions.

@coderabbitai

coderabbitai Bot commented Mar 9, 2026

Copy link
Copy Markdown

Important

Review skipped

Draft detected.

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

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2fb7d4ca-3371-493d-a764-72228cf901b1

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

Walkthrough

The changes enhance default value handling for Pydantic v2 union types. When a field references a type alias or contains an inline union of BaseModels with a dict default value, the code now generates TypeAdapter-based validation to properly validate the default against the entire union, rather than leaving it as a raw dict or validating only against the first union member.

Changes

Cohort / File(s) Summary
Core union default validation logic
src/datamodel_code_generator/model/pydantic_base.py
Adds logic to detect type aliases pointing to BaseModel unions and inline unions with dict defaults. Generates TypeAdapter-based validators using TypeAdapter(alias_name).validate_python(default) or TypeAdapter(Union[...]).validate_python(default) and sets flags _type_adapter_import_needed and _union_import_for_type_adapter.
Pydantic v2 import integration
src/datamodel_code_generator/model/pydantic_v2/imports.py, src/datamodel_code_generator/model/pydantic_v2/base_model.py
Defines new IMPORT_TYPE_ADAPTER constant for pydantic.TypeAdapter. Conditionally includes IMPORT_TYPE_ADAPTER and IMPORT_UNION in field imports based on validation flags set during default handling.
Test expected outputs
tests/data/expected/main/jsonschema/pydantic_v2_multi_model_union_default_object.py, tests/data/expected/main/jsonschema/pydantic_v2_multi_model_union_default_object_type_alias.py, tests/data/expected/main/jsonschema/ref_union_default_object.py
New test data files demonstrating generated Pydantic v2 models with TypeAdapter-validated union defaults using default_factory=lambda: TypeAdapter(Union[...]).validate_python({...}).
Test cases
tests/main/jsonschema/test_main_jsonschema.py
Adds three new test functions validating TypeAdapter behavior for union defaults with and without --use-type-alias, guarded by Black version compatibility check.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

breaking-change-analyzed, breaking-change

Poem

🐰 A rabbit hops through unions with glee,
TypeAdapter validates each mystery,
Dicts transform to models so fine,
No more raw defaults, all types align! ✨

🚥 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 directly and clearly describes the main change: using TypeAdapter for validating union dict defaults in both type alias and inline union scenarios, which is the core fix implemented across the codebase.
Linked Issues check ✅ Passed All code changes directly address the two linked issues: #3034 (type alias union defaults) and #3035 (inline union validation). The implementation adds TypeAdapter validation logic for both scenarios as required.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing the two identified issues: enhancing default value handling in pydantic_base.py, adding necessary imports in pydantic_v2 modules, and adding comprehensive test coverage for the fixes.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% 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 unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/type-alias-union-default-dict

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

github-actions Bot commented Mar 9, 2026

Copy link
Copy Markdown
Contributor

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

@codecov

codecov Bot commented Mar 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.18919% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 99.97%. Comparing base (3c244da) to head (738f3e0).

Files with missing lines Patch % Lines
...rc/datamodel_code_generator/model/pydantic_base.py 80.95% 0 Missing and 4 partials ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##              main    #3041      +/-   ##
===========================================
- Coverage   100.00%   99.97%   -0.03%     
===========================================
  Files           85       85              
  Lines        17684    17720      +36     
  Branches      2068     2078      +10     
===========================================
+ Hits         17684    17716      +32     
- Partials         0        4       +4     
Flag Coverage Δ
unittests 99.97% <89.18%> (-0.03%) ⬇️

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/type-alias-union-default-dict branch from 4fdbf7e to 738f3e0 Compare March 9, 2026 08:03
@koxudaxi koxudaxi marked this pull request as draft March 9, 2026 08:03
@koxudaxi koxudaxi closed this Mar 9, 2026
@codspeed-hq

codspeed-hq Bot commented Mar 9, 2026

Copy link
Copy Markdown

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/type-alias-union-default-dict (738f3e0) with main (3c244da)

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 deleted the fix/type-alias-union-default-dict branch June 21, 2026 14:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant