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

`SyntaxError: from __future__ imports must occur at the beginning of the file` when custom header is used

Open Dezzley opened this issue 6 months ago • 0 comments

Describe the bug When a model is generated with a custom header, importing the resulting model module causes the following error:

SyntaxError: from __future__ imports must occur at the beginning of the file

This error occurs because the from __future__ statement must appear near the top of the module (see documentation)

To Reproduce Generate model via the provided command below using any schema:

Used commandline:

$  datamodel-codegen --input "./openapi.yml" --input-file-type openapi --output ./model.py --output-model-type pydantic_v2.BaseModel --snake-case-field --target-python-version 3.10 --use-schema-description --use-field-description  --base-class CustomBaseModel --custom-file-header-path ./custom_pydantic_file_header.py

Expected behavior Generated module could be imported without any issues.

Version:

  • OS: MacOS Sonoma 14.6.1
  • Python version: 3.10.14
  • datamodel-code-generator version: 0.25.9

Additional context Consider hoisting the future statement if any custom header option is passed.

Dezzley avatar Aug 22 '24 15:08 Dezzley