dapper91 / pydantic-xml

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

Python 3.10 pipe Union type hints not supported #56

Closed jwfraustro closed 1 year ago

jwfraustro commented 1 year ago

Currently, the Model1 | Model2 Python 3.10 syntax of a union is not recognized between models by pydantic-xml.

This can be replicated pretty easily by changing the TestModel class here to use them: https://github.com/dapper91/pydantic-xml/blob/68ce0480c1c691d1742f479b919872bd4dba730d/tests/test_unions.py#L32-L40 as in:

    class TestModel(BaseXmlModel, tag='model'):
        field1: SubModel1 | SubModel2 = element()

this will fail when .from_xml() is called (and in testing my project, when to_xml() is called also) with

 >   ???
E   pydantic.error_wrappers.ValidationError: 1 validation error for TestModel
E   field1
E     field required (type=value_error.missing)

pydantic/main.py:341: ValidationError

The cause for this is this function: https://github.com/dapper91/pydantic-xml/blob/68ce0480c1c691d1742f479b919872bd4dba730d/pydantic_xml/serializers/serializer.py#L69-L70

Unions denoted by the | in Python 3.10 are actually types.UnionType rather than typing.Union.

typing.get_origin() actually returns it specifically:



https://github.com/python/cpython/blob/a5d2b546c1b0b73d0695b98838a3ddd497382999/Lib/typing.py#L2412-L2413



The fix is just adding UnionType to the is_union() function.