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

Generated models can contain name clash

Open andrzej-pomirski-yohana opened this issue 6 months ago • 0 comments

Describe the bug When generating models for a schema that contains a field called "date" with

type: string
format: date

and the field not being required the resulting class is invalid, since it contains a definition as such:

date: date | None = None

and Python complains about it:

E   TypeError: unsupported operand type(s) for |: 'NoneType' and 'NoneType'
E   Unable to evaluate type annotation 'date | None'.

To Reproduce

Example schema:

ExampleSchema:
  properties:
    date:
      type: string
      format: date
  required: []

Used commandline:

poetry run datamodel-codegen --input schema.yml --output models.py

and the following settings in pyproject.toml:

[tool.datamodel-codegen]
input-file-type = "openapi"
output-model-type = "pydantic_v2.BaseModel"
enum-field-as-literal = "one"
target-python-version = "3.12"
use-one-literal-as-default = true
use-generic-container-types = true
use-standard-collections = true
use-union-operator = true
use-double-quotes = true
reuse-model = true
wrap-string-literal = true
strict-nullable = true
snake-case-field = true

Expected behavior Instead of using

from datetime import date

do

import datetime

and then, in the definition, do

date: datetime.date | None = None

However, this also requires any fields of the datetime type to be annotated as datetime.datetime and will break if there's any fields called datetime in the schema. So alternatively (and probably more recommended), change the field name (e.g. contain a trailing underscore) during generation and use an alias.

Version:

  • OS: macOS
  • Python version: 3.12.8
  • datamodel-code-generator version: 0.28.5

Additional context Add any other context about the problem here.

andrzej-pomirski-yohana avatar May 07 '25 13:05 andrzej-pomirski-yohana