Repository navigation
Write a field --type-overrides value with brackets, such as typing.Literal[1, 2], as the annotation it spells - #5352
Conversation
…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
|
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
|
| 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:
Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Bug fix
Possibly related issues
- Issue 4747 concerns broken
Literaloverride behavior, including bracket parsing, float literals, and optional literals. This change covers those override cases.
Possibly related PRs
- datamodel-code-generator/datamodel-code-generator#5246: Both PRs use annotation constraint resolution when determining which constraints an override supports.
- datamodel-code-generator/datamodel-code-generator#5207: Both PRs change the field type override pass.
Merge Risk: 
Minimal · up to d7ae2
-
The float override is intentionally preserved, and no actionable issue remains before normal merge checks.
Pre-merge checks: 
5
-
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.
Comment @coderabbitai help to get the list of available commands.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour 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. |
Merging this PR will degrade performance by 17.59%2 warnings
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing Footnotes
|
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`.
Breaking Change AnalysisResult: 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 |
…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
Refs: #4747
Summary by CodeRabbit
Literalvalues, imported members, and optional or nullable types. Generated fields preserve supported constraints and optionality.