Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Pydantic Generic Basemodel Validation Error

$
0
0

Pydantic Generic BaseModels fails unexpectedly when validating python instances but succeeds when validating the same data as a dictionary.

Python: 3.11.8Pydantic: 2.7.1

Here is the Generic Model:

from typing import Generic, TypeVarfrom pydantic import BaseModelU = TypeVar("U")class M1(BaseModel, Generic[U]):    a: list[U]    b: list[U]class M2(BaseModel):    a: str    m1: M1[int]

It works when validating a raw dictionary:

m2 = M2.model_validate(    {"a": "s","m1": {"a": [1],"b": [2]        }    })

However, it does not work when using python types:

m2 = M2(    a="s",    m1=M1(        a=[1],        b=[2]    ))  # fails :(

Interestingly enough, the following also fails:

m2 = M2.model_validate(    dict(        a="s",        m1=M1(            a=[1],            b=[2]        )    ))

Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>