datamodel-code-generator
datamodel-code-generator copied to clipboard
Avoid constrained types such as `conint()`
trafficstars
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
- #2213 discusses some other issues caused when using Pydantic 2, although these deprecations are probably not as serious
- #2018 discusses how the output code can be much simpler and cleaner by embracing
Annotated, although it doesn't discuss the context of deprecated syntax