datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Strict types don't enforce field constraints

Open colinbr96 opened this issue 11 months ago • 0 comments

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:

  1. Omit the --field-constraints option, which uses conint for enforcing constraints. But it fails to pass MyPy with the error "Invalid type comment or annotation".
  2. 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 pass strict=True.

colinbr96 avatar Mar 13 '24 21:03 colinbr96