Skip to content

use_union_operator=True does not work with specific field names #2964

@matejscerba

Description

@matejscerba

Describe the bug

When using flag use_union_operator=True and specific field names (e.g. float), that are not required, Pydantic typing fails and the generated model can not be used. Setting use_union_operator to False works as expected.

To Reproduce

Example schema:

openapi: 3.1.0
paths: {}
components:
  schemas:
    ReservedProperty:
      type: object
      properties:
        float:
          type: number
          format: float

Used commandline:

$ datamodel-codegen --input <path to the file above>

The command above generates the following content:

from __future__ import annotations

from pydantic import BaseModel


class ReservedProperty(BaseModel):
    float: float | None = None

When trying to instantiate the class (a = ReservedProperty()), I get the following error:

TypeError: unsupported operand type(s) for |: 'NoneType' and 'NoneType'

It appears that field name float clashes with float type.

Expected behavior

I expect the generated file to be usable within Python without any errors.

Version:

  • OS: macOS Tahoe 26.1
  • Python version: 3.13.5
  • datamodel-code-generator version: 0.52.2

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions