Pydantic: When doing a union of types with the same contract, items are converted inappropriately

Created on 2 Apr 2019  路  1Comment  路  Source: samuelcolvin/pydantic

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:

  • OS: Linux
  • Python version 3.7.1
  • Pydantic version 0.21
feature request

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_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.

>All comments

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_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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nav picture nav  路  3Comments

samuelcolvin picture samuelcolvin  路  3Comments

iwoloschin picture iwoloschin  路  3Comments

timonbimon picture timonbimon  路  3Comments

bartekbrak picture bartekbrak  路  3Comments