[Python] Python pydantic xml with TypeVar and Generic Type model is partially initialized

Discussão em 'Python' iniciado por Stack, Maio 26, 2025.

  1. Stack

    Stack Membro Participativo

    I'm new to python and I'm tasked in building a fastapi service that returns an xml format of a model/class in python. I'm using pydantic_xml with TypeVar and Generic but keep getting the error 'model is partially initialized'

    >>> from pydantic_xml import BaseXmlModel, element
    >>>
    >>> from typing import TypeVar, Generic
    >>>
    >>> T = TypeVar('T')
    >>>
    >>> class Data(BaseXmlModel, Generic[T]):
    ...
    ... data:T = element(tag='data')
    ...
    >>>
    >>> class Result(BaseXmlModel):
    ...
    ... total: int = element(default = 0)
    ... data: Data = element(default = None)
    ...
    >>>
    >>> data = Data(data = [1,2,3,4])
    >>> result = Result(total = 0, data = data)
    >>>
    >>> print(result.to_xml())
    Traceback (most recent call last):
    File "<python-input-166>", line 1, in <module>
    print(result.to_xml())
    ~~~~~~~~~~~~~^^
    File "/Users/las/Projects/ds-hcm/rip-service-hcm-recruitment/.venv/lib/python3.13/site-packages/pydantic_xml/model.py", line 604, in to_xml
    self.to_xml_tree(skip_empty=skip_empty, exclude_none=exclude_none, exclude_unset=exclude_unset),
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/Users/ads/Projects/ds-hcm/rip-service-hcm-recruitment/.venv/lib/python3.13/site-packages/pydantic_xml/model.py", line 577, in to_xml_tree
    self.__xml_serializer__.serialize(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
    root, self, pdc.to_jsonable_python(
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<6 lines>...
    exclude_unset=exclude_unset,
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
    File "/Users/ads/Projects/ds-hcm/rip-service-hcm-recruitment/.venv/lib/python3.13/site-packages/pydantic_xml/serializers/factories/model.py", line 179, in serialize
    field_serializer.serialize(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~^
    element, getattr(value, field_name), encoded[field_name],
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<2 lines>...
    exclude_unset=exclude_unset,
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
    File "/Users/ads/Projects/ds-hcm/rip-service-hcm-recruitment/.venv/lib/python3.13/site-packages/pydantic_xml/serializers/factories/model.py", line 394, in serialize
    assert self._model.__xml_serializer__ is not None, f"model {self._model.__name__} is partially initialized"
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    AssertionError: model Data is partially initialized


    I have read the this discussion but can't seem to understand how to implement it.

    Appreciate any help.

    Continue reading...

Compartilhe esta Página