Skip to content
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

When doing a union of types with the same contract, items are converted inappropriately #453

Closed
JakeSummers opened this issue Apr 2, 2019 · 3 comments · Fixed by #2092
Closed

Comments

@JakeSummers
Copy link

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
@samuelcolvin
Copy link
Member

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.

@OrBin
Copy link

OrBin commented Apr 7, 2021

@samuelcolvin do you have any plans on solving this?

@PrettyWood
Copy link
Member

@OrBin #2092 is open. You can try it out and see if this solves your issue

alexdrydew pushed a commit to alexdrydew/pydantic that referenced this issue Dec 23, 2023
* coverage only on 3.11

* remove rm rust-toolchain

* remove rm rust-toolchain, more
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants