Skip to content

Fix handling of falsy default values for enums in set-default-enum-member option#2977

Merged
koxudaxi merged 6 commits intokoxudaxi:mainfrom
kkinugasa:fix/2976-falsy-default-enum-number
Feb 7, 2026
Merged

Fix handling of falsy default values for enums in set-default-enum-member option#2977
koxudaxi merged 6 commits intokoxudaxi:mainfrom
kkinugasa:fix/2976-falsy-default-enum-number

Conversation

@kkinugasa
Copy link
Copy Markdown
Contributor

@kkinugasa kkinugasa commented Feb 2, 2026

Fixes: #2976

Summary by CodeRabbit

  • Bug Fixes

    • Corrected enum member matching so falsy defaults (e.g., 0, empty string, False) are honored rather than treated as absent.
  • Tests

    • Added test coverage validating default enum member selection for falsy default values in JSON Schema generation.
  • Samples

    • Added expected output illustrating enums and a model using falsy default enum members.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 2, 2026

📝 Walkthrough

Walkthrough

Updated enum default handling so falsy defaults (e.g., 0, "") are treated as valid enum members instead of being coerced away; adjusted checks to distinguish None from other falsy values and added tests + expected output for falsy-default enum members.

Changes

Cohort / File(s) Summary
Enum matching logic
src/datamodel_code_generator/model/enum.py
Compute field_default using "" if field.default is None else field.default so falsy defaults (0, '') are preserved for member matching.
Parser default check
src/datamodel_code_generator/parser/base.py
Changed conditional from if not model_field.default to if model_field.default is None so non-None falsy defaults are processed for enum member assignment.
Tests — CLI integration
tests/main/jsonschema/test_main_jsonschema.py
Added test_main_jsonschema_falsy_default_enum_member to exercise --set-default-enum-member with falsy defaults.
Tests — Expected output
tests/data/expected/main/jsonschema/falsy_default_enum_member.py
New expected fixture defining enums and a model where falsy defaults are set to enum members (e.g., Status.integer_0, Name.field_, Active.boolean_False).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested labels

breaking-change-analyzed, breaking-change

Poem

🐰 I hopped through defaults, small and sly,
Zero and empty no longer pass by.
With None distinguished, the members align,
Enums now greet their rightful sign—
A tiny hop, and the code feels spry!

🚥 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 pull request title clearly and concisely describes the main change: fixing handling of falsy default values for enums with the set-default-enum-member option.
Linked Issues check ✅ Passed All coding requirements from issue #2976 are met: field default handling changed from truthiness to None check in parser/base.py, enum member value matching updated in model/enum.py, and test coverage added.
Out of Scope Changes check ✅ Passed All changes directly address the bug fix described in issue #2976; no out-of-scope modifications detected.

✏️ 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

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.

Copy link
Copy Markdown
Collaborator

@ilovelinux ilovelinux left a comment

Choose a reason for hiding this comment

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

It looks good but we need a unit test to cover that edge case. It will help us to verify the fix and prevent any future regressions 🙂

@kkinugasa
Copy link
Copy Markdown
Contributor Author

Thanks for the suggestion. I’ve added a unit test to cover that falsy default enum edge case to verify the fix and help prevent future regressions.

@kkinugasa kkinugasa requested a review from ilovelinux February 2, 2026 15:03
@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Feb 2, 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 kkinugasa:fix/2976-falsy-default-enum-number (1ee71db) 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 2, 2026

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #2977   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           94        94           
  Lines        17780     17782    +2     
  Branches      2044      2044           
=========================================
+ Hits         17780     17782    +2     
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.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a bug where falsy default values (0, False, empty string) for enum fields were not being converted to their corresponding enum members when using the --set-default-enum-member flag. The issue occurred because the code was using truthy checks (if not model_field.default) instead of explicit None checks (if model_field.default is None).

Changes:

  • Fixed condition in __set_default_enum_member to check for None explicitly instead of using truthy evaluation
  • Fixed string conversion in find_member to handle falsy values correctly
  • Added test coverage for falsy default values (integer 0 and empty string)

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated no comments.

Show a summary per file
File Description
src/datamodel_code_generator/parser/base.py Changed falsy check to explicit None check in __set_default_enum_member
src/datamodel_code_generator/model/enum.py Fixed default value conversion to handle None separately from falsy values in find_member
tests/main/jsonschema/test_main_jsonschema.py Added test for falsy default enum values
tests/data/jsonschema/falsy_default_enum_number.json Test input with integer 0 and empty string defaults
tests/data/expected/main/jsonschema/falsy_default_enum_number.py Expected output showing correct enum member assignment

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/main/jsonschema/test_main_jsonschema.py Outdated
Comment thread src/datamodel_code_generator/model/enum.py Outdated
@kkinugasa kkinugasa requested a review from ilovelinux February 3, 2026 00:33
ilovelinux
ilovelinux previously approved these changes Feb 3, 2026
Copy link
Copy Markdown
Collaborator

@ilovelinux ilovelinux left a comment

Choose a reason for hiding this comment

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

Good job! LGTM!

@ilovelinux ilovelinux requested a review from koxudaxi February 3, 2026 10:31
@koxudaxi koxudaxi merged commit 9554fb6 into koxudaxi:main Feb 7, 2026
38 of 40 checks passed
@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, not a breaking change. The changes fix incorrect handling of falsy default values (0, "", False) when using the --set-default-enum-member option. Previously, falsy defaults were incorrectly treated as absent/None due to Python's truthiness evaluation (not model_field.default and field.default or ""). The fix changes these to explicit None checks (model_field.default is None and if field.default is None else). While this does change generated output for schemas with falsy enum defaults, it corrects the behavior to match what users would expect - the enum member reference is now properly set as the default. This is fixing a bug to align with documented feature behavior, not changing intended functionality.


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.

Enum default=0 is not converted to enum member with --set-default-enum-member

4 participants