Skip to content

Write a field --type-overrides value with brackets, such as typing.Literal[1, 2], as the annotation it spells - #5352

Merged
Koudai Aono (koxudaxi) merged 2 commits into
fix-5348-alias-default-variantfrom
fix-4747-literal-overrides
Oct 26, 2026
Merged

Koudai Aono (koxudaxi) merged 2 commits into
fix-5348-alias-default-variantfrom
fix-4747-literal-overrides

Conversation

@koxudaxi

@koxudaxi Koudai Aono (koxudaxi) commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Refs: #4747

Summary by CodeRabbit

  • New Features
    • Bracketed type overrides now accept Python annotations, including Literal values, imported members, and optional or nullable types. Generated fields preserve supported constraints and optionality.
  • Bug Fixes
    • Constraint handling is more consistent when an override changes a field’s type; unsupported constraints are not carried over.
  • Documentation
    • Clarified how factory-style and bracketed annotation overrides handle constraints.

…teral[1, 2], as the annotation it spells

A field override was split at its last dot as a class path, so a value with brackets was written as a class of
the module before the dot: `typing.Literal[1, 2]` imported `Literal[1, 2]` from `typing`, `typing.Literal[5.5]`
imported `5]` from `typing.Literal[5` and left the field as `5]`, and `typing.Literal[http.HTTPStatus.OK]`
imported `OK]` from `typing.Literal[http.HTTPStatus`. The module failed to import with a SyntaxError, and
msgspec wrote `Meta(ge=...)` on the `Literal`, which it does not take.

A field override whose value holds brackets and spells an annotation is now written as `x-python-type` writes
that annotation: its names are imported (`from http import HTTPStatus` for an enum member, `Optional` and
`Literal` from `typing`), the field keeps the None its schema admits, and the field takes the keywords that
annotation takes, so msgspec writes no `Meta` on a `Literal` and a list of them keeps the list keywords. A
Pydantic output without `--field-constraints` drops the `con*` arguments of the replaced type and warns, as for
a class override. A value without brackets, and every run without `--type-overrides`, keep their output; a
model-level override with brackets and GraphQL input keep the output they had.

Refs: #4747
@coderabbitai

coderabbitai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 750112e and d7ae221.

Files ignored due to path filters: 10
  • docs/llms-full.txt is excluded by none and included by none
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_annotations[dataclasses.dataclass-extra_args4].payloads.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_annotations[msgspec.Struct-extra_args6].warnings.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_annotations[pydantic_v2.BaseModel-extra_args0].warnings.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_members[dataclasses.dataclass-extra_args3].payloads.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_members[pydantic_v2.BaseModel-extra_args0].warnings.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/jsonschema/type_overrides_literal_members.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/type_overrides_literals.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/payloads/type_overrides_literal_members.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/payloads/type_overrides_literals.json is excluded by !tests/data/**/*.json and included by none
Files selected for processing: 18
  • docs/field-constraints.md
  • src/datamodel_code_generator/parser/base.py
  • src/datamodel_code_generator/parser/jsonschema.py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_annotations[dataclasses.dataclass-extra_args4].py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_annotations[msgspec.Struct-extra_args6].py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_annotations[pydantic_v2.BaseModel-extra_args0].py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_annotations[pydantic_v2.BaseModel-extra_args1].py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_annotations[pydantic_v2.BaseModel-extra_args2].py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_annotations[pydantic_v2.dataclass-extra_args3].py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_annotations[typing.TypedDict-extra_args5].py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_members[dataclasses.dataclass-extra_args3].py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_members[pydantic_v2.BaseModel-extra_args0].py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_members[pydantic_v2.BaseModel-extra_args1].py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_members[pydantic_v2.dataclass-extra_args2].py
  • tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_members[typing.TypedDict-extra_args4].py
  • tests/main/jsonschema/test_main_jsonschema.py
  • tests/main/jsonschema/test_main_jsonschema.refs
  • tests/main/test_payload_validation.refs

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

Walkthrough

Bracketed --type-overrides values are parsed as Python annotations and applied to fields. Constraint tracking accounts for the replacement annotation. Tests cover literal values, imported members, generated models, and payload validation.

Changes: Annotation-valued type overrides

Layer / File(s) Summary
Parse annotations and update field constraints
src/datamodel_code_generator/parser/base.py, src/datamodel_code_generator/parser/jsonschema.py, docs/field-constraints.md
The JSON Schema parser recognizes bracketed overrides as annotations and applies them while preserving optionality. Shared logic tracks constraints supported by the replacement type and records dropped constraints. The documentation describes how annotation overrides differ from factory overrides.
Cover literal annotation overrides
tests/main/jsonschema/test_main_jsonschema.py, tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_annotations*.py, tests/main/jsonschema/test_main_jsonschema.refs, tests/main/test_payload_validation.refs
Tests and generated snapshots cover literal annotations, optional and nullable values, constraint variants, multiple output backends, and payload validation.
Cover literals with imported members
tests/main/jsonschema/test_main_jsonschema.py, tests/data/expected/main/jsonschema/main_jsonschema/main_type_overrides_literal_members*.py, tests/main/jsonschema/test_main_jsonschema.refs
Tests and generated snapshots cover float literals and dotted imported members, including HTTP status values and a client port constant.

Priority: Normal

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

Change: Bug fix

Possibly related issues

  • Issue 4747 concerns broken Literal override behavior, including bracket parsing, float literals, and optional literals. This change covers those override cases.

Possibly related PRs

Merge Risk: Minimal · up to d7ae2

The float override is intentionally preserved, and no actionable issue remains before normal merge checks.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: bracketed --type-overrides values such as typing.Literal[1, 2] are now parsed and written as the annotation they spell, instead of being split at the last dot as class…
Docstring Coverage Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 13 files. (5 skipped: 3 …
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.
Full details: Title check

Explanation

The title names the main change: bracketed --type-overrides values such as typing.Literal[1, 2] are now parsed and written as the annotation they spell, instead of being split at the last dot as class paths. The raw summary confirms this in JsonSchemaParser, base.py, and the Literal annotation and member test fixtures. The title is specific and does not use vague terms. It omits the Pydantic constraint-dropping detail, which the title does not need to cover.

Full details: Docstring Coverage

Explanation

Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 13 files. (5 skipped: 3 unsupported, 2 too large.)

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T07:41:10.219263Z d7ae221 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

Copy link
Copy Markdown
Contributor

@codspeed

codspeed Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 17.59%

2 warnings

⚠️ Walltime results may be unreliable

Some benchmarks used the Walltime instrument outside CodSpeed Macro Runners, which can make the results inconsistent.

Learn more about Macro Runners

See affected benchmarks

⚠️ Base and head ran on different runner types

Some benchmarks with significant performance changes were compared across different runner types, so the changes might not come from the code. Run base and head on the same runner type, or use CodSpeed Macro Runners for more stable results.

Learn more about Macro Runners

Open the report in CodSpeed to investigate

❌ 40 regressed benchmarks
✅ 10 untouched benchmarks
⏩ 98 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_perf_recommend_options_full_kubernetes_style 17.3 s 24.3 s -28.72%
❌ test_perf_load_pyproject_config[mapping-None] 291.3 µs 375.3 µs -22.38%
❌ test_perf_client_calls[async] 37.1 ms 47.7 ms -22.35%
❌ test_perf_load_pyproject_config[config-None] 288.2 µs 367.3 µs -21.52%
❌ test_perf_target_render[fastapi-large] 5.6 s 7.1 s -21.5%
❌ test_perf_load_pyproject_config[mapping-multiple] 299.6 µs 381.6 µs -21.49%
❌ test_perf_load_pyproject_config[config-multiple] 301.1 µs 379.9 µs -20.73%
❌ test_perf_target_render[client-large] 6.8 s 8.6 s -20.53%
❌ test_perf_deep_nested 5.3 s 6.6 s -20%
❌ test_perf_client_calls[sync] 33.7 ms 42.1 ms -19.86%
❌ test_perf_extreme_large_schema 14.9 s 18.5 s -19.58%
❌ test_perf_all_options_enabled 6.1 s 7.6 s -19.35%
❌ test_perf_complex_refs 2.1 s 2.6 s -19.12%
❌ test_perf_stripe_style_pydantic_v2 2.1 s 2.5 s -18.83%
❌ test_perf_false_reference_validation 315.8 ms 388.3 ms -18.67%
❌ test_perf_large_models_pydantic_v2 3.5 s 4.3 s -18.04%
❌ test_perf_multiple_files_input 3.6 s 4.4 s -17.83%
❌ test_perf_kubernetes_style_pydantic_v2 2.6 s 3.1 s -17.65%
❌ test_perf_aws_style_openapi_pydantic_v2 2.1 s 2.5 s -17.29%
❌ test_perf_graphql_style_pydantic_v2 819 ms 987.3 ms -17.04%
... ... ... ... ...

ℹ️ Only the first 20 benchmarks are displayed. Go to the app to view all benchmarks.

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing fix-4747-literal-overrides (e261e84) with fix-5348-alias-default-variant (750112e)

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

codecov Bot commented Oct 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

… without the discriminator

A union that names one variant alone by its `$ref` rewrote the variant's
one-value Enum tag as its `Literal`, and an optional `Literal` tag as required
with its value as default. That changed the field of a model that 0.86.0 wrote
and that worked on its own: a Pydantic dataclass whose type alias was never
used imported, and its tag held the Enum member.

The lone variant now keeps its model as 0.86.0 wrote it, and
`settle_discriminated_unions` writes the union without `discriminator=`, as it
does for a lone variant whose tag is no `Literal`. Pydantic validates the tag
through the variant's own field either way. The tags of variants that nested
choices give a union are still written as their `Literal`.
@koxudaxi
Koudai Aono (koxudaxi) merged commit d872b69 into main Oct 26, 2026
131 of 132 checks passed
@koxudaxi
Koudai Aono (koxudaxi) deleted the fix-4747-literal-overrides branch October 26, 2026 07:48
@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: The PR makes two behavioral changes, and both fix output that was broken before. First, a type-overrides value with brackets, such as a typing Literal annotation, is now written as an annotation, like x-python-type. Per the test docstrings, up to 0.86.0 such a value was split at its last dot and produced modules that failed to import, so this turns broken output into working output. Overrides without brackets still use the base parser path unchanged. Second, the lone discriminator variant handling in the modules pass drops the post-0.86.0 rewriting of the single variant's tag into a Literal with a default. The variant model now keeps the tag field it declares, as 0.86.0 wrote it per the updated test docstring, and the union is written without discriminator= where Pydantic cannot use the field as a tag. Under 0.86.0 such a union with a one-value Enum tag failed at import, so relative to the last release this is a fix. It is not certain what 0.86.0 generated for the lone-variant-tags fixtures, where an empty payload is now accepted and the Shared tag loses its default; that judgment relies on the PR's own statement that these models match 0.86.0. The only removed code items are a private helper keyword argument and private method signatures. No CLI options, public API, templates or Python version support are removed or changed incompatibly.


This analysis was produced by the release draft workflow

Koudai Aono (koxudaxi) added a commit that referenced this pull request Oct 27, 2026
…such as typing.Literal[1, 2], as the annotation it spells (#5391)

A model-level entry with brackets, such as {"Level": "typing.Literal[1, 2]"}, was split at its last dot as a
class path like a field entry was before #5352: the module imported `Literal[1, 2]` from `typing`, a float left
`5]` and an enum member `OK]` (`from typing.Literal[http.HTTPStatus import OK]`), and the module failed to import
with a SyntaxError. A field or scalar entry of a GraphQL input broke the same way, since only the JSON Schema
parser bound an annotation.

Each field that names the overridden model now takes the annotation, written as `x-python-type` writes it: its
names are imported (`from http import HTTPStatus` for an enum member, `Optional` and `Literal` from `typing`),
also where the model is in another module. The binding of an annotation and the field override move from
JsonSchemaParser to Parser, so a GraphQL field override with brackets is written the same way. A value without
brackets and every run without `--type-overrides` keep their output.

Refs: #4747
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.

1 participant