dapper91 / pydantic-xml

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

Union based on Literal discrimination does not seem to work #140

Closed phdowling closed 8 months ago

phdowling commented 8 months ago

Sample code:

from typing import Literal, Union
from pydantic_xml import BaseXmlModel, attr, element

class A(BaseXmlModel):
    inner: Literal["a"] = attr()

class B(BaseXmlModel):
    inner: Literal["a"] = attr()

class UnionModel(BaseXmlModel):
    prop: Union[A, B] = element()

x1 = UnionModel.from_xml('<UnionModel><prop inner="a"></prop></UnionModel>')  # works
x2 = UnionModel.from_xml('<UnionModel><prop inner="b"></prop></UnionModel>')
# pydantic_core._pydantic_core.ValidationError: 1 validation error for B
# inner
#   Input should be 'a' [type=literal_error, input_value='b', input_type=str]
#     For further information visit https://errors.pydantic.dev/2.4/v/literal_error

Apologies if I am getting something wrong here, but shouldn't the second string parse just as well as the first one?

phdowling commented 8 months ago

My bad, this example actually works, obviously I just had the same literal in both classes here. I still have an issue in my codebase but the code above clearly does not reproduce my issue, so I can't rule out that I just have a bug elsewhere - closing for now.