Skip to content

Avoid constrained types such as conint() #2313

@multimeric

Description

@multimeric

Describe the bug
Python's type specification no longer allows for function calls directly in type annotations, as discussed here. However, in an effort to keep the generator compatible with Pydantic 1, constructions such as x: conint() are still created, which is not actually valid Python.

I think there needs to be a Pydantic 2+ flag that can relax the need for backwards compatibility, and use newer more valid constructs like Annotated[]

To Reproduce

Example schema:

openapi: 3.1.0
info:
  title: Constraints
  version: '1.0'
components:
  schemas:
    dayInYear:
      type: integer
      minimum: 1
      maximum: 365

Used commandline:

datamodel-codegen --input openapi.yml

Actual output

from __future__ import annotations

from pydantic import BaseModel, conint


class DayInYear(BaseModel):
    __root__: conint(ge=1, le=365)

Expected behavior
There should be a flag such as --pydantic-2 or --pydantic 2+ that instead outputs:

from typing_extensions import Annotated
from pydantic import BaseModel, Field

class DayInYear(BaseModel):
    __root__: Annotated[int, Field(ge=1, le=365)

Version:

  • OS: Pop!_OS 22.04 LTS
  • Python version: Python 3.13.1
  • datamodel-code-generator version: 0.27.2

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions