Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strict types don't enforce field constraints #1884

Open
colinbr96 opened this issue Mar 13, 2024 · 0 comments
Open

Strict types don't enforce field constraints #1884

colinbr96 opened this issue Mar 13, 2024 · 0 comments

Comments

@colinbr96
Copy link

colinbr96 commented Mar 13, 2024

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant