[Python] Unable to create a nested DefaultDict in a pydantic BaseModel

Discussão em 'Python' iniciado por Stack, Maio 15, 2025.

  1. Stack

    Stack Membro Participativo

    Consider:

    import pydantic
    from typing import Annotated
    from collections import defaultdict
    from uuid import UUID

    class Repro(pydantic.BaseModel):
    value: Annotated[
    defaultdict[UUID, defaultdict[UUID, dict]],
    pydantic.Field(
    default_factory=lambda: defaultdict[UUID, defaultdict[UUID, dict]](lambda: defaultdict(dict))
    ),
    ]

    # to validate that the typechecker thinks the above are valid:
    instance = Repro(value=defaultdict[UUID, defaultdict[UUID, dict]](lambda: defaultdict(dict)))


    The above passes type checking with pyright, but at runtime, the class definition fails while pydantic is trying to introspect the object's schema:


    pydantic.errors.PydanticSchemaGenerationError: Unable to infer a default factory for keys of type <class 'dict'>. Only str, int, bool, list, dict, frozenset, tuple, float, set are supported, other types require an explicit default factory set using `DefaultDict[..., Annotated[..., Field(default_factory=...)]]
    ​

    Thinking it might be introspection of the inner defaultdict triggering the error message, I tried adding a pydantic.Field to its type via an inner annotation:

    class Repro(pydantic.BaseModel):
    value: Annotated[
    defaultdict[
    UUID, Annotated[defaultdict[UUID, dict], pydantic.Field(default_factory=dict)]
    ],
    pydantic.Field(default_factory=lambda: defaultdict[UUID, defaultdict[UUID, dict]](lambda: defaultdict(dict))),
    ]


    ...but with identical effect.


    The above is observed with Python 3.12 and Pydantic 2.11.0, type-checked with pyright 1.1.382.

    Continue reading...

Compartilhe esta Página