Skip to content

Fix optional discriminator literals#3608

Open
koxudaxi wants to merge 3 commits into
mainfrom
agent/fix-optional-discriminator-literals
Open

Fix optional discriminator literals#3608
koxudaxi wants to merge 3 commits into
mainfrom
agent/fix-optional-discriminator-literals

Conversation

@koxudaxi

@koxudaxi koxudaxi commented Jul 16, 2026

Copy link
Copy Markdown
Owner

Fixes: #3606

Summary by CodeRabbit

  • Bug Fixes

    • Improved Pydantic v2 discriminated unions when required fields are forced to be optional, including correct discriminator defaulting and null/required behavior.
    • Preserved correct generation for both standard models and dataclass outputs, with better handling when discriminator types collapse to a single literal/enum member.
  • Tests

    • Added OpenAPI generation fixtures and assertions covering discriminator optionality, enum-value discriminator usage, and integer enum mappings.
    • Added dynamic model validation coverage for forced-optional discriminator literals.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 44a9bc00-bf1c-4781-a947-3971c64b7a2d

📥 Commits

Reviewing files that changed from the base of the PR and between e64bc09 and 0a4370a.

⛔ Files ignored due to path filters (2)
  • tests/data/expected/dynamic_models/force_optional_discriminator_literals.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/openapi/discriminator_force_optional.yaml is excluded by !tests/data/**/*.yaml and included by none
📒 Files selected for processing (7)
  • src/datamodel_code_generator/parser/base.py
  • tests/data/expected/main/openapi/discriminator/enum_single_value_anyof_use_enum_force_optional.py
  • tests/data/expected/main/openapi/discriminator/force_optional_pydantic_v2_dataclass.py
  • tests/data/expected/main/openapi/discriminator/integer_mapping_use_enum_force_optional.py
  • tests/main/openapi/test_main_openapi.py
  • tests/main/test_dynamic_models.py
  • tox.ini
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/data/expected/main/openapi/discriminator/force_optional_pydantic_v2_dataclass.py
  • tests/main/test_dynamic_models.py

📝 Walkthrough

Walkthrough

Changes

The parser now assigns literal or enum-member defaults to forced-optional Pydantic v2 discriminator fields while preserving non-nullable Literal types. Generated fixtures and tests cover base models, dataclasses, enum mappings, dynamic generation, and OpenAPI output.

Optional discriminator handling

Layer / File(s) Summary
Apply optional discriminator defaults
src/datamodel_code_generator/parser/base.py
Discriminator defaults are resolved from single literals or enum members; matching Pydantic v2 fields become non-required and non-nullable while msgspec handling remains separate.
Generate discriminator model outputs
tests/data/expected/main/openapi/discriminator/*
Expected Pydantic v2 base-model, dataclass, enum, integer-mapping, and optional-union outputs reflect literal discriminator defaults.
Validate discriminator generation
tests/main/test_dynamic_models.py, tests/main/openapi/test_main_openapi.py, tox.ini
Dynamic-model and OpenAPI tests validate generated models and golden files, with the new tests registered in the Pydantic test environment.

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

Possibly related PRs

🚥 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 Concise, specific, and matches the main fix for optional discriminator literals.
Linked Issues check ✅ Passed The parser fix and added Pydantic v2 tests directly address the discriminator-needs-literal failure under force_optional_for_required_fields.
Out of Scope Changes check ✅ Passed The changes are centered on the discriminator optionality bug and its tests; no unrelated features appear in the summary.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/fix-optional-discriminator-literals

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.

@koxudaxi
koxudaxi marked this pull request as ready for review July 16, 2026 15:49
@github-actions

Copy link
Copy Markdown
Contributor

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

@codspeed-hq

codspeed-hq Bot commented Jul 16, 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.

✅ 13 untouched benchmarks
⏩ 98 skipped benchmarks1


Comparing agent/fix-optional-discriminator-literals (0a4370a) with main (eb65a56)

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/datamodel_code_generator/parser/base.py (1)

2045-2052: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Update the type hint to accept Enum members.

To cleanly support using Enum values as the discriminator default when use_enum_values_in_discriminator=True, literal should also accept Member.

♻️ Proposed refactor
     def __set_force_optional_discriminator_literal_default(
         self,
         model: DataModel,
         discriminator_field: DataModelFieldBase,
-        literal: DiscriminatorValue,
+        literal: DiscriminatorValue | Member,
         *,
         can_retain_cache: bool,
     ) -> None:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/datamodel_code_generator/parser/base.py` around lines 2045 - 2052, Update
the literal parameter type hint in
__set_force_optional_discriminator_literal_default to accept Enum Member values
in addition to DiscriminatorValue, preserving the existing behavior and other
parameter types.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/datamodel_code_generator/parser/base.py`:
- Around line 2152-2171: Update the discriminator resolution flow around
_is_msgspec_struct and replace_field_type: only take the early-break path for
msgspec structs, preserving replace_field_type and discriminator_field.required
updates for Pydantic v2 models. Move
__set_force_optional_discriminator_literal_default to after the
replace_field_type block so it runs for every resolved Pydantic discriminator
field, including fields whose literals were inferred from a non-literal schema.

---

Nitpick comments:
In `@src/datamodel_code_generator/parser/base.py`:
- Around line 2045-2052: Update the literal parameter type hint in
__set_force_optional_discriminator_literal_default to accept Enum Member values
in addition to DiscriminatorValue, preserving the existing behavior and other
parameter types.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f0b500ac-7e2c-4ef9-b39e-6a8cd7a7cf63

📥 Commits

Reviewing files that changed from the base of the PR and between 5381743 and e64bc09.

⛔ Files ignored due to path filters (2)
  • tests/data/expected/dynamic_models/force_optional_discriminator_literals.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/openapi/discriminator_force_optional.yaml is excluded by !tests/data/**/*.yaml and included by none
📒 Files selected for processing (7)
  • src/datamodel_code_generator/parser/base.py
  • tests/data/expected/main/openapi/discriminator/force_optional_pydantic_v2.py
  • tests/data/expected/main/openapi/discriminator/force_optional_pydantic_v2_dataclass.py
  • tests/data/expected/main/openapi/discriminator/required_pydantic_v2.py
  • tests/main/openapi/test_main_openapi.py
  • tests/main/test_dynamic_models.py
  • tox.ini

Comment thread src/datamodel_code_generator/parser/base.py
@codecov

codecov Bot commented Jul 16, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (5381743) to head (0a4370a).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #3608   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          164       164           
  Lines        35647     35725   +78     
  Branches      4106      4121   +15     
=========================================
+ Hits         35647     35725   +78     
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 Harness.
📢 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.

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