koxudaxi / datamodel-code-generator

Pydantic model and dataclasses.dataclass generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.
https://koxudaxi.github.io/datamodel-code-generator/
MIT License
2.44k stars 281 forks source link

AttributeError: 'FieldInfo' object has no attribute '<EnumName>' #1982

Closed alpoi-x closed 2 weeks ago

alpoi-x commented 1 month ago

Describe the bug Generating from a schema with an Enum type causes AttributeError: 'FieldInfo' object has no attribute '<EnumName>'

To Reproduce File structure after codegen should look like:

schemas/
├─ bean.json
├─ bean_type.json
src/
├─ __init__.py
├─ bean.py
├─ bean_type.py
main.py

With the schemas defined as follows: schemas/bean.json

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "bean.json",
  "type": "object",
  "title": "Bean",
  "properties": {
    "beanType": { "$ref": "bean_type.json" },
    "name": { "type": "string" }
  },
  "additionalProperties": false,
  "required": ["beanType", "name"]
}

schemas/bean_type.json

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "bean_type.json",
  "title": "BeanType",
  "additionalProperties": false,
  "enum": ["STRING_BEAN", "RUNNER_BEAN", "GREEN_BEAN", "BAKED_BEAN"]
}

and

main.py

from src.bean import Bean

if __name__ == "__main__":
    pass

Used commandline

$ datamodel-codegen \
    --use-title-as-name \
    --use-standard-collections \ 
    --snake-case-field \
    --target-python-version 3.12 \
    --input schemas \
    --input-file-type jsonschema \
    --output src

Expected behavior Exactly what happened, except we should then be able to import and use the generated classes. Instead, an AttributeError is raised.

Version:

Additional context In the generated file src/bean.py, if we manually change from . import bean_type to from .bean_type import BeanType, and the corresponding usage in the Bean class definition, the error disappears. Might be related to #1683 / #1684