Example:
from typing import Union
import pydantic
class A(pydantic.BaseModel):
x: str
class B(pydantic.BaseModel):
x: str
class MyModel(pydantic.BaseModel):
attr: Union[B, A]
m = MyModel(attr=A(x="apples"))
print(m)
m = MyModel(attr=B(x="apples"))
print(m)
This prints:
MyModel attr=<B x='apples'>
MyModel attr=<B x='apples'>
Expected output:
MyModel attr=<A x='apples'>
MyModel attr=<B x='apples'>
Workaround: One workaround is to ensure that your classes do not have equivalent signatures. Changing to this will avoid the issue:
class A(pydantic.BaseModel):
a_x: str
class B(pydantic.BaseModel):
b_x: str
System Info:
3.7.10.21This is the same as #436.
We could perhaps iterate over self.sub_fields and try to find a type match as well as validation pass first, however I'd be worried it would make this critical piece of code slower. Maybe possible through a config switch.
Most helpful comment
This is the same as #436.
https://github.com/samuelcolvin/pydantic/blob/085fc8481807a3f9cd162fea397079334bd7f849/pydantic/fields.py#L407-L412
We could perhaps iterate over
self.sub_fieldsand try to find a type match as well as validation pass first, however I'd be worried it would make this critical piece of code slower. Maybe possible through a config switch.