OpenAPITools / OpenAPITools/openapi-generator

[BUG] [Python] [Pydantic] Generated from_dict() incorrectly calls List[...] as a function for nested arrays

Open
#21,309 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

Description

openapi-generator produces broken Python code when generating models with nested arrays, such as in a MultiPolygon structure.

The generated model looks like this:

class MultiPolygon(BaseModel):
    bbox: Optional[Bbox] = None
    coordinates: List[List[Annotated[List[LineStringCoordinatesInner], Field(min_length=4)]]]
    type: StrictStr

But in the generated from_dict() method, it incorrectly tries to call List[...] as a function:

"coordinates": [
    [List[LineStringCoordinatesInner].from_dict(_inner_item) for _inner_item in _item]
    for _item in obj["coordinates"]
]
Model Class
class RoofLayerFeature(geojson_pydantic.Feature):
    pass
Generated DTO class
class MultiPolygon(BaseModel):
    """
    MultiPolygon Model
    """ # noqa: E501
    bbox: Optional[Bbox] = None
    coordinates: List[List[Annotated[List[LineStringCoordinatesInner], Field(min_length=4)]]]
    type: StrictStr
    __properties: ClassVar[List[str]] = ["bbox", "coordinates", "type"]

    # ...

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of MultiPolygon from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate({
            "bbox": Bbox.from_dict(obj["bbox"]) if obj.get("bbox") is not None else None,
            "coordinates": [
                    [List[LineStringCoordinatesInner].from_dict(_inner_item) for _inner_item in _item]
                    for _item in obj["coordinates"]
                ] if obj.get("coordinates") is not None else None,
            "type": obj.get("type")
        })
        return _obj

This leads to a runtime error since List[...] is not callable.
openapi-generator version

@openapitools/openapi-generator-cli@7.11.0

Steps to Reproduce

Generate a Python client using a schema that includes a deeply nested array (like MultiPolygon) and try to use the generated from_dict() method. It will fail due to misuse of List[...] as a constructor.

Currently I'm using fastapi + https://github.com/developmentseed/geojson-pydantic

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the Python generator entry point that produces model from_dict() methods and reproduce the nested-array MultiPolygon case described in the issue. Trace how nested List and Annotated types are rendered, then verify that generated code uses a callable model conversion and that the from_dict() runtime path succeeds without calling List[...] itself.

Written by the indexing model from the issue text.

Assessment

Tech stack
fastapi, openapi, python
Domain
api, backend-api-design
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
56/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.