Skip to content

Fix enum member default resolution#3303

Merged
koxudaxi merged 9 commits into
mainfrom
fix-enum-member-default-resolution
Jun 10, 2026
Merged

Fix enum member default resolution#3303
koxudaxi merged 9 commits into
mainfrom
fix-enum-member-default-resolution

Conversation

@koxudaxi

@koxudaxi koxudaxi commented Jun 10, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • Bug Fixes

    • Corrected enum member resolution to properly evaluate and compare default values across different types (strings, integers, booleans), ensuring consistent member identification
    • Improved handling of discriminator-based mappings when using enum-typed schema fields
  • New Features

    • Added optional string-to-value coercion mode for enum member lookup to enhance flexibility when matching enum members

@coderabbitai

coderabbitai Bot commented Jun 10, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR improves enum member resolution by replacing string-quote heuristics with AST-based literal evaluation and JSON-semantics equality comparison. The parser uses these changes to resolve discriminator values to enum members with string coercion, allowing numeric and string defaults to match correctly.

Changes

Enum member resolution and discriminator coercion

Layer / File(s) Summary
Enum member resolution core logic
src/datamodel_code_generator/model/enum.py
Adds ast import and introduces evaluate_member_value (parses string defaults as Python literals via ast.literal_eval) and _json_value_equal (JSON-style equality: numeric types compare by value, booleans are type-sensitive). Rewrites Enum.find_member to evaluate and compare member defaults, with optional coerce_strings parameter for string-to-non-string matching.
Parser discriminator integration
src/datamodel_code_generator/parser/base.py
Imports evaluate_member_value and updates _create_discriminator_data_type and _get_enum_discriminator_literal to use find_member(..., coerce_strings=True) for discriminator value resolution and derive discriminator literals from evaluated runtime enum defaults.
Unit tests for find_member and discriminator literal
tests/parser/test_base.py
Updates find_member test cases for integer/string/mixed enums to verify coercion-only matching for numeric strings; adds assertions confirming quoted-value representations fail default lookups; introduces test_get_enum_discriminator_literal_with_escaped_value to verify unescaped default resolution.
Generated test fixtures
tests/data/expected/main/jsonschema/dataclass_enum_member_special_defaults.py, tests/data/expected/main/jsonschema/enum_member_typed_defaults.py
Adds two fixture modules: a dataclass with Mode and Quoted enum defaults; a Pydantic model with StrOne and IntTwo enum-member defaults.
End-to-end CLI tests
tests/main/jsonschema/test_main_jsonschema.py
Adds two integration tests generating dataclass and Pydantic BaseModel output from enum-default JSON schemas, verifying output correctness and module importability.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

breaking-change-analyzed, breaking-change

Poem

🐰 Enums were lost in quote-stripping haze,
Now ast.literal_eval lights the maze,
JSON equality makes numbers align,
Discriminators coerce—a cleaner design!
Booleans stay true to their type, not a lie.

🚥 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 'Fix enum member default resolution' directly describes the main change: improving how enum member defaults are resolved in the codebase.
Docstring Coverage ✅ Passed Docstring coverage is 82.35% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-enum-member-default-resolution

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 Jun 10, 2026

Copy link
Copy Markdown
Contributor

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

@codspeed-hq

codspeed-hq Bot commented Jun 10, 2026

Copy link
Copy Markdown

Merging this PR will improve performance by 28.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.

⚡ 11 improved benchmarks
⏩ 98 skipped benchmarks1

Performance Changes

Mode Benchmark BASE HEAD Efficiency
WallTime test_perf_stripe_style_pydantic_v2 1.9 s 1.5 s +30.4%
WallTime test_perf_aws_style_openapi_pydantic_v2 1.8 s 1.4 s +29.95%
WallTime test_perf_openapi_large 2.7 s 2.1 s +29.1%
WallTime test_perf_graphql_style_pydantic_v2 754.8 ms 585 ms +29.01%
WallTime test_perf_duplicate_names 989.5 ms 767 ms +29.01%
WallTime test_perf_kubernetes_style_pydantic_v2 2.5 s 1.9 s +29%
WallTime test_perf_complex_refs 1.9 s 1.4 s +28.66%
WallTime test_perf_all_options_enabled 4.9 s 3.9 s +28.11%
WallTime test_perf_deep_nested 4.7 s 3.7 s +28.01%
WallTime test_perf_multiple_files_input 3.4 s 2.6 s +27.28%
WallTime test_perf_large_models_pydantic_v2 3.4 s 2.7 s +25.84%

Tip

Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.


Comparing fix-enum-member-default-resolution (6b16cad) with main (f204def)

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.

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

codecov Bot commented Jun 10, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff             @@
##              main     #3303    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files          116       116            
  Lines        26248     26364   +116     
  Branches      3328      3336     +8     
==========================================
+ Hits         26248     26364   +116     
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.

@koxudaxi koxudaxi force-pushed the fix-enum-member-default-resolution branch from 2644c62 to fc37cbb Compare June 10, 2026 09:47
@koxudaxi koxudaxi force-pushed the fix-enum-member-default-resolution branch from fc37cbb to c5ce4b5 Compare June 10, 2026 09:51
@koxudaxi koxudaxi enabled auto-merge (squash) June 10, 2026 17:09
@koxudaxi koxudaxi merged commit 6cad701 into main Jun 10, 2026
51 checks passed
@koxudaxi koxudaxi deleted the fix-enum-member-default-resolution branch June 10, 2026 17:28
@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: PR #3303 is a bug fix that corrects enum member default resolution. The changes to find_member() behavior (stricter type-aware matching, proper evaluation of string literals) fix incorrect behavior where defaults with special characters, mixed-type enums, or quoted values were resolved wrongly or not at all. The new coerce_strings parameter defaults to False (the correct strict behavior) and is set to True only internally for OpenAPI discriminator lookups. Generated code output only changes in cases where it was previously incorrect. These are correctness improvements, not behavioral changes that break previously working correct usage.


This analysis was performed by Claude Code Action

@github-actions

Copy link
Copy Markdown
Contributor

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

2 participants