New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
GenericModel[Any] raises ValidationError for GenericModel[SomeModel] #9414
Comments
gsakkis
added
bug V2
Bug related to Pydantic V2
pending
Awaiting a response / confirmation
labels
May 8, 2024
Hi @gsakkis, Thanks for your questions. This comment might help to add some context regarding some of the nuances with validation and parametrized generics: #8884 (comment). The case with from typing import Any, Generic, TypeVar
from pydantic import BaseModel, ValidationError
T = TypeVar("T")
class ResponseModel(BaseModel, Generic[T]):
content: T
class Product(BaseModel):
name: str
price: float
class Order(BaseModel):
id: int
product: ResponseModel[Any]
# replacing the previous annotation with the following succeeds at runtime but fails type checking
# product: ResponseModel
product = Product(name="Apple", price=0.5)
response1: ResponseModel[Any] = ResponseModel[Any](content=product)
response2: ResponseModel[Any] = ResponseModel(content=product)
response3: ResponseModel[Any] = ResponseModel[Product](content=product)
for response in response1, response2, response3:
try:
order = Order(id=1, product=response.model_dump())
print(f"{response!r} succeeded")
except ValidationError:
print(f"{response!r} failed") I'm going to chat with @dmontagu, our resident generics expert, about this and will get back to you! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Initial Checks
Description
Annotating a field as
ResponseModel[Any]
(whereResponseModel
is a generic BaseModel) fails to validate values of typeResponseModel
andResponseModel[Product]
; it only validates values ofResponseModel[Any]
.On the other hand annotating the field as
ResponseModel
validates all three cases, however mypy givesMissing type parameters for generic type "ResponseModel"
.Questions:
ResponseModel[Any]
validation working as expected or it's a bug?# type: ignore
the second version that seems to be working?Example Code
Output:
Python, Pydantic & OS Version
The text was updated successfully, but these errors were encountered: