dapper91 / pydantic-xml

python xml for humans
https://pydantic-xml.readthedocs.io
The Unlicense
141 stars 14 forks source link

Order not respected in union of types including str #127

Closed maurosilber closed 9 months ago

maurosilber commented 9 months ago

According to the docs, the order of the types in the union is respected. But when using str, it seems that it always wins:

from pydantic_xml import BaseXmlModel, attr

class Model(BaseXmlModel):
    x: float | bool = attr()
    y: bool | float = attr()
    z: str | float = attr()
    w: float | str = attr()

Model.from_xml("<Model x='1' y='1' z='1' w='1' />")

Output:

Model(x=1.0, y=True, z='1', w='1')

Expected:

Model(x=1.0, y=True, z='1', w=1.0)
dapper91 commented 9 months ago

@maurosilber Hi.

The order of the types in the union is respected except the case when the input type matches one of the union types. I agree that is not very intuitive but that is how pydantic itself works. Here you can read more about that.

I will mention that in the documentation, thanks.

To fix you problem pass left_to_right union_mode to the w field:

class Model(BaseXmlModel):
    x: float | bool = attr()
    y: bool | float = attr()
    z: str | float = attr()
    w: float | str = attr(union_mode='left_to_right')
maurosilber commented 9 months ago

Thank you!

I was not aware of that behaviour, as I'm not quite familiar with pydantic.

I've opened a PR updating the docs.