The code below outputs:
Caught A
Missed B
Although it should catch both validations. Generic model which is marked as optional seems to fail type checks, and produces "Any" type instead.
Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":
pydantic version: 1.7.3
pydantic compiled: True
install path: /opt/virtualenvs/python3/lib/python3.8/site-packages/pydantic
python version: 3.8.7 (default, Dec 21 2020, 20:10:35) [GCC 7.5.0]
platform: Linux-5.4.0-1019-gcp-x86_64-with-glibc2.27
optional deps. installed: ['typing-extensions']
from typing import TypeVar, Generic, Optional, List
from pydantic import BaseModel
from pydantic.generics import GenericModel
DataT = TypeVar('DataT')
class Data(BaseModel):
foo: str
# --- WORKS ---
class APIContentS(GenericModel, Generic[DataT]):
"""Second-level for the API response. i.e. the content"""
data: DataT
message: Optional[str] = None
class APIResponseS(GenericModel, Generic[DataT]):
"""Base API response model"""
payload: APIContentS[DataT]
is_successful: bool = True
try:
model = APIResponseS[List[Data]](
payload=APIContentS(
data=[{'bar': True}]
)
)
print("Missed A")
except:
print("Caught A")
# --- FAILS ---
class APIContent(GenericModel, Generic[DataT]):
"""Second-level for the API response. i.e. the content"""
data: Optional[DataT]
message: Optional[str] = None
class APIResponse(GenericModel, Generic[DataT]):
"""Base API response model"""
payload: APIContent[DataT]
is_successful: bool = True
try:
model = APIResponse[List[Data]](
payload=APIContent(
data=[{'bar': True}]
)
)
print("Missed B")
except:
print("Caught B")
Hi @Mazyod
There is already an opened PR #1989 solving a lot of issues on generic models.
It also solves your issue :)
The fix will be available in pydantic 1.8 for sure 馃憤
Happy new year 馃帀
Most helpful comment
Hi @Mazyod
There is already an opened PR #1989 solving a lot of issues on generic models.
It also solves your issue :)
The fix will be available in pydantic 1.8 for sure 馃憤
Happy new year 馃帀