Skip to content

TypeStatement.jinja2 crashes with "list object has no element 0" when use_type_alias=True + reuse_model=True on large specs #3059

@mkaay

Description

@mkaay

Description

When using use_type_alias=True together with reuse_model=True on large OpenAPI specs, the TypeStatement.jinja2 template crashes with list object has no element 0. This happens because reuse_model can create TypeStatement models with an empty fields list, but the template unconditionally accesses fields[0] on line 11.

Error

jinja2.exceptions.UndefinedError: list object has no element 0

Traceback points to TypeStatement.jinja2 line 11:

type {{ class_name }} = {{ get_type_annotation(fields[0]) }}

Reproduction

The bug triggers on large, real-world OpenAPI specs where reuse_model deduplicates enough schemas that some get converted to TypeStatement with empty fields. I was not able to produce a minimal synthetic repro — the interaction between reuse_model and schema deduplication requires a critical mass of schemas.

Using the public Amazon Advertising Sponsored Products spec (669 schemas):

from pathlib import Path
from datamodel_code_generator import DataModelType, LiteralType, PythonVersion, generate

# Download the spec first:
# curl -o sp_v3.json 'https://d1y2lf8k3vrkfu.cloudfront.net/openapi/en-us/dest/SponsoredProducts_prod_3p.json'

generate(
    input_=Path("sp_v3.json"),
    output=Path("output.py"),
    output_model_type=DataModelType.PydanticV2BaseModel,
    target_python_version=PythonVersion.PY_314,
    use_type_alias=True,
    reuse_model=True,
    enum_field_as_literal=LiteralType.All,
    use_annotated=True,
    field_constraints=True,
)

Other Amazon Advertising specs that also crash: Sponsored Brands, Sponsored Display, DSP Campaigns, DSP Creatives.

Suggested fix

Guard the fields[0] access in TypeStatement.jinja2:

{%- if fields %}
type {{ class_name }} = {{ get_type_annotation(fields[0]) }}{% if comment is defined %}  # {{ comment }}{% endif %}
{%- if description %}
...
{%- endif %}
{%- else %}
type {{ class_name }} = {{ base_class }}{% if comment is defined %}  # {{ comment }}{% endif %}
{%- if description %}
...
{%- endif %}
{%- endif %}

Environment

  • datamodel-code-generator version: 0.55.0
  • Python: 3.14

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