Skip to content

Fix missing | None for nullable enum literals in TypedDict#2991

Merged
koxudaxi merged 5 commits intomainfrom
fix/nullable-enum-literal-typed-dict
Feb 14, 2026
Merged

Fix missing | None for nullable enum literals in TypedDict#2991
koxudaxi merged 5 commits intomainfrom
fix/nullable-enum-literal-typed-dict

Conversation

@koxudaxi
Copy link
Owner

@koxudaxi koxudaxi commented Feb 14, 2026

Fixes: #2986

Summary by CodeRabbit

  • Bug Fixes

    • Generated models now represent nullable enums correctly: None is included in enum literals where present and optional/nullability flags propagate to fields and model types.
  • Tests

    • Added a test covering nullable enum literals in TypedDict generation and updated expected model outputs to reflect nullable enum handling.

@coderabbitai
Copy link

coderabbitai bot commented Feb 14, 2026

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

parse_enum_as_literal now excludes literal None from Literal members and marks the resulting DataType as optional when None/null is present in the JSON Schema enum, causing generated Literal types to be emitted as Literal[...] | None for nullable enums; tests and expected outputs updated.

Changes

Cohort / File(s) Summary
Parser Logic
src/datamodel_code_generator/parser/jsonschema.py
Modify parse_enum_as_literal to build Literal values from enum entries excluding None/null and set DataType.is_optional = True when None/null is present, so nullable enums become `Literal[...]
TypedDict JSON Schema tests & expected output
tests/data/expected/main/jsonschema/typed_dict_nullable_enum_literal.py, tests/main/jsonschema/test_main_jsonschema.py
Add expected TypedDict model and test asserting nullable enums are emitted as `Literal[...]
OpenAPI enum expected outputs
tests/data/expected/main/openapi/enum_models/all.py, tests/data/expected/main/openapi/enum_models/as_literal.py
Update expected OpenAPI-generated enum model roots to include `

Sequence Diagram(s)

(skip — changes are parser-only and do not introduce multi-component sequential flows)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

breaking-change-analyzed

Suggested reviewers

  • ilovelinux

Poem

🐰 A hop, a nibble, a tiny cheer,
Enums learned to hold a None so dear.
Literals stretch and TypeAlias grows wide,
TypedDicts now let nullable values inside. 🥕

🚥 Pre-merge checks | ✅ 6
✅ Passed checks (6 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Fix missing | None for nullable enum literals in TypedDict' is concise, specific, and directly reflects the main change: fixing nullable enum literals in TypedDict output.
Linked Issues check ✅ Passed The PR successfully addresses all coding requirements from issue #2986: nullable enum TypeAliases include '| None', required inline enum fields are nullable, and optional inline enum fields within NotRequired are nullable.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing nullable enum literals in TypedDict: the core parser fix, the new test file with expected output, the test case, and updates to existing enum test fixtures.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into main

✏️ 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
  • Commit unit tests in branch fix/nullable-enum-literal-typed-dict

No actionable comments were generated in the recent review. 🎉


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
Copy link
Contributor

github-actions bot commented Feb 14, 2026

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/datamodel_code_generator/parser/jsonschema.py`:
- Around line 3529-3534: In parse_enum_as_literal, guard against enums that are
all-None by first building literals = [i for i in obj.enum if i is not None] and
is_optional = None in obj.enum, then if literals is empty and is_optional is
True return a None-only DataType (i.e., construct and return self.data_type that
represents a None-only enum — for example with empty literals and
is_optional=True) instead of returning a potentially invalid empty Literal;
otherwise return the normal self.data_type(literals=literals,
is_optional=is_optional).

@codecov
Copy link

codecov bot commented Feb 14, 2026

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #2991   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           94        94           
  Lines        18065     18068    +3     
  Branches      2090      2090           
=========================================
+ Hits         18065     18068    +3     
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.

@koxudaxi koxudaxi merged commit 2b659f0 into main Feb 14, 2026
36 of 37 checks passed
@koxudaxi koxudaxi deleted the fix/nullable-enum-literal-typed-dict branch February 14, 2026 05:25
@github-actions
Copy link
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: This PR is a bug fix that corrects generated code to include | None for enum types that contain null in their values. Previously, when a schema defined an enum like enum: ["red", "amber", "green", null, 42], the generated code incorrectly produced Literal['red', 'amber', 'green', 42] (dropping the nullability). Now it correctly produces Literal['red', 'amber', 'green', 42] | None. This is not a breaking change because: (1) the old output was incorrect - it didn't match the schema semantics, (2) the new output is the correct representation of a nullable enum, and (3) existing code that relied on the old behavior was technically incorrect since the schema allows null values. Bug fixes that correct generated output to match schema definitions are not considered breaking changes.


This analysis was performed by Claude Code Action

@github-actions
Copy link
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.

Nullable enums from JSON Schema to TypedDicts are missing | None

1 participant

Comments