Skip to content

repeated imports not at top of generated file / redefinition of some classes #3597

Description

@bkcsfi

Describe the bug

The .py file generated from the attached openapi spec contains repeated import statements and some class definitions are redefined later in the .py file.

e.g.

Image

Its possible that the openap spec file is not well formed, that may be the cause of this issue. I don't have control over the openapi file itself, I can't change it.

To Reproduce

Run the command line shown below

Example schema:

customscity-2.0.1.json

Used commandline:

$ datamodel-codegen --input customscity-2.0.1.json \
      --output-model-type pydantic_v2.BaseModel  --target-pydantic-version 2.12 \
      --snake-case-field --openapi-scopes schemas parameters paths \
      --allow-extra-fields --use-standard-collections --use-union-operator \
      --force-optional --allow-population-by-field-name \
      --target-python-version=3.14 --collapse-root-models \
      --use-schema-description --capitalise-enum-members \
      --enable-version-header --use-annotated \
      --output-datetime-class datetime \
      --formatters ruff-check ruff-format \
      > customscity_201_import.py

Expected behavior

I expect all the import statements to be at the top of the generated file, and for none of the class names to be redefined.

Instead I get this output file:

customscity_201_import.py

Version:

  • OS: Debian Trixie in devcontainer
  • Python version: 3.14
  • datamodel-code-generator version: 0.68.1

Additional context

This project is a life saver, thank you very much for building this program.

I can hand edit the generated file to work around this issue, so its not a critical problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions