Skip to content

Map OpenAPI Discriminator mapping's values to their real value in enums #3074

Draft
ilovelinux wants to merge 2 commits intokoxudaxi:mainfrom
ilovelinux:fix/ilovelinux-3073-enum-literal-values
Draft

Map OpenAPI Discriminator mapping's values to their real value in enums #3074
ilovelinux wants to merge 2 commits intokoxudaxi:mainfrom
ilovelinux:fix/ilovelinux-3073-enum-literal-values

Conversation

@ilovelinux
Copy link
Copy Markdown
Collaborator

@ilovelinux ilovelinux commented Apr 5, 2026

Context

  • OpenAPI Discriminator mapping field is a key-value dictionary.
  • Both the keys and the values of the dictionary must be strings.
  • Despite they are strings, the mapping happens:
    1. Converting any received value to string.
    2. Comparing the converted value with the keys in the dictionary.

Ref: https://swagger.io/specification/#options-for-mapping-values-to-schemas

What's changed

  • Now mapping's keys are mapped to their real enum values, if available
  • Otherwise, old behavior kicks-in

Notes

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of discriminator fields to properly resolve multiple mapped values
    • Enhanced discriminator type generation for complex inheritance scenarios

@ilovelinux ilovelinux self-assigned this Apr 5, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 5, 2026

📝 Walkthrough

Walkthrough

This PR fixes integer discriminator handling in OpenAPI schema generation. When a discriminator property has multiple enum values, the parser now correctly generates integer literals instead of string literals, and refactors the discriminator value resolution logic based on a use_enum_values_in_discriminator flag.

Changes

Cohort / File(s) Summary
Discriminator Logic Refactoring
src/datamodel_code_generator/parser/base.py
Refactored discriminator data type creation to branch on use_enum_values_in_discriminator: when enabled, preserves enum-field-name behavior; when disabled, resolves discriminator values to mapped enum members' defaults (stripping quoted defaults for string-like cases). Simplified control flow by removing conditional gating around enum source lookup in get_discriminator_field_value.
Test Fixture Updates
tests/data/expected/main/openapi/discriminator/integer_mapping.py
Added IntEnum member integer_3 = 3 to Kind1 and expanded Bar.kind discriminator type from Literal[2] to Literal[2, 3], fixing the generation of integer literals for multi-value integer discriminators.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • PR #3070: Modifies discriminator handling in src/datamodel_code_generator/parser/base.py with related changes to how enum-backed discriminators are resolved.

Suggested labels

breaking-change-analyzed, breaking-change

Suggested reviewers

  • koxudaxi

Poem

🐰 A hop, a skip, through enum space,
Where integers lost their rightful place—
No more as strings do they pretend,
Literals fixed, from start to end!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.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.
Linked Issues check ✅ Passed The PR implementation directly addresses issue #3073 by mapping discriminator values to real enum types (integers) instead of string literals, as evidenced by the code changes mapping discriminator values through enum resolution.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the discriminator enum-value mapping issue: refactoring discriminator data type creation logic and updating corresponding test expectations.
Title check ✅ Passed The title clearly identifies the main change: mapping OpenAPI discriminator mapping values to real enum values instead of string literals, which directly corresponds to the core objective of the PR.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Apr 5, 2026

Merging this PR will degrade performance by 21.57%

⚠️ 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.

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

❌ 11 regressed benchmarks
⏩ 98 skipped benchmarks1

⚠️ Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Mode Benchmark BASE HEAD Efficiency
WallTime test_perf_kubernetes_style_pydantic_v2 2.2 s 2.8 s -18.73%
WallTime test_perf_aws_style_openapi_pydantic_v2 1.6 s 2 s -19.05%
WallTime test_perf_large_models_pydantic_v2 3.1 s 3.9 s -20.72%
WallTime test_perf_complex_refs 1.8 s 2.3 s -20.38%
WallTime test_perf_graphql_style_pydantic_v2 706.7 ms 871.4 ms -18.9%
WallTime test_perf_multiple_files_input 3.1 s 3.9 s -20.15%
WallTime test_perf_all_options_enabled 5.6 s 6.9 s -18.66%
WallTime test_perf_duplicate_names 900.1 ms 1,121.9 ms -19.77%
WallTime test_perf_stripe_style_pydantic_v2 1.7 s 2.1 s -18.49%
WallTime test_perf_openapi_large 2.5 s 3.2 s -21.57%
WallTime test_perf_deep_nested 5.2 s 6.5 s -19.75%

Comparing ilovelinux:fix/ilovelinux-3073-enum-literal-values (a07509f) with main (5ba49a7)

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 Apr 5, 2026

Codecov Report

❌ Patch coverage is 95.65217% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 99.99%. Comparing base (5ba49a7) to head (a07509f).

Files with missing lines Patch % Lines
src/datamodel_code_generator/parser/base.py 95.65% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##              main    #3074      +/-   ##
===========================================
- Coverage   100.00%   99.99%   -0.01%     
===========================================
  Files           87       87              
  Lines        18237    18244       +7     
  Branches      2087     2091       +4     
===========================================
+ Hits         18237    18243       +6     
- Partials         0        1       +1     
Flag Coverage Δ
unittests 99.99% <95.65%> (-0.01%) ⬇️

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.

@ilovelinux
Copy link
Copy Markdown
Collaborator Author

ilovelinux commented Apr 5, 2026

This PR is draft because of the following tasks:

@ilovelinux ilovelinux marked this pull request as draft April 5, 2026 19:14
@ilovelinux ilovelinux changed the title Draft: Map OpenAPI Discriminator mapping's values to their real value in enums Map OpenAPI Discriminator mapping's values to their real value in enums Apr 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OpenAPI integer discriminator with multiple enum values generates string Literals

1 participant