datamodel-code-generator
datamodel-code-generator copied to clipboard
Strict types don't enforce field constraints
Describe the bug
When using —strict-types
and --field-constraints
(or --use-annotated
) together, the field constraints are not added to the Field.
To Reproduce
Example schema:
components:
schemas:
Timestamp:
type: integer
minimum: 1
maximum: 9999999999
Used commandline:
$ datamodel-codegen --input api.yaml --output models.py --input-file-type openapi --output-model-type pydantic_v2.BaseModel --field-constraints --strict-types int
Expected behavior Generates the model
class Timestamp(RootModel[StrictInt]):
root: StrictInt = Field(..., ge=1, le=9999999999)
Actual behavior Generates the model
class Timestamp(RootModel[StrictInt]):
root: StrictInt
Version:
- OS: RedHat Linux
- Python version: Python 3.11.7
- datamodel-code-generator version: 0.25.3
Additional context There's a few workarounds, but both are undesirable:
- Omit the
--field-constraints
option, which usesconint
for enforcing constraints. But it fails to pass MyPy with the error "Invalid type comment or annotation". - Avoid using strict field attributes and enforce Pydantic strict mode via
Timestamp.model_validate('123', strict=True)
. But then the generated model is vulnerable if we forget to passstrict=True
.