Skip to content

Homogeneous element of tagged unions stops on first failure #276

@DenSinH

Description

@DenSinH

So I have a model which contains a list of a tagged union. However, I would really like to have some sort of catch-all or failure whenever a tagged-union element cannot be determined. The current behavior is that the loading just stops. At the very least, I would like it to keep loading, but a catch-all would be best. Consider the following example:

from pydantic_xml import BaseXmlModel, element, attr
from typing import Literal, Annotated
from pydantic import Field


class Pet(BaseXmlModel, tag="pet"):
    pet_type: str = Field()  # must be filled by child class


class Cat(Pet):
    pet_type: Literal['cat'] = attr(default="cat")


class Dog(Pet):
    pet_type: Literal['dog'] = attr(default="dog")


class Lizard(Pet):
    pet_type: Literal['lizard'] = attr(default="lizard")


AnyPet = Annotated[
    Cat | Dog | Lizard,
    Field(discriminator="pet_type")
]


class House(BaseXmlModel, tag="house"):
    pets: list[AnyPet] = element()


house = House.from_xml("""
<house>
    <pet pet_type="cat"/>
    <pet pet_type="dog"/>
    <pet pet_type="cow"/>
    <pet pet_type="lizard"/>
</house>
""")
print(house)
# prints
# pets=[Cat(pet_type='cat'), Dog(pet_type='dog')]

Note that the loading stops as soon as it hits an unknown tag ("cow"). I would prefer it to either crash, or at least continue loading.

To get it to continue loading, I think simply removing the break from the following line would work:0

but an error would be best.

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions