pydantic-xml icon indicating copy to clipboard operation
pydantic-xml copied to clipboard

Correct way to get tag name in xml_field_serializer

Open eltoder opened this issue 11 months ago • 2 comments

In the code below I'm writing a custom serializer for list[int] fields. In the serializer I need to know the tag name of the field, rather than the field name. These are not the same because tag names contain dashes (-), so I had to rename them:

import pydantic_xml as pxml

class Model(pxml.BaseXmlModel):
    x_ids: list[int] = pxml.element(tag="x-ids")
    y_ids: list[int] = pxml.element(tag="y-ids")

    @pxml.xml_field_serializer("x_ids", "y_ids")
    def _serialize_ids(self, elem, value, field):
        # need the tag name ("x-ids" or "y-ids") here

What is the recommended way to get the tag name?

eltoder avatar Mar 25 '25 18:03 eltoder

@eltoder Hi,

Tag name is not passed to the serializer directly, but you are able to extract it from the model field metadata:

import pydantic_xml as pxml

class Model(pxml.BaseXmlModel):
    x_ids: list[int] = pxml.element(tag="x-ids")
    y_ids: list[int] = pxml.element(tag="y-ids")

    @pxml.xml_field_serializer("x_ids", "y_ids")
    def _serialize_ids(self, elem, value, field):
        tag_name = self.model_fields[field].path

dapper91 avatar Mar 29 '25 07:03 dapper91

Thanks! This works, but mypy complains:

t.py:10: error: "FieldInfo" has no attribute "path"  [attr-defined]

eltoder avatar Mar 30 '25 16:03 eltoder

You may check the field_info type before:

@pxml.xml_field_serializer("x_ids", "y_ids")
    def _serialize_ids(self, elem, value, field):
        if isinstance(field_info := self.model_fields[field], pxml.fields.XmlEntityInfo):
            tag_name = self.model_fields[field].path
        else:
            ...

dapper91 avatar Jun 22 '25 07:06 dapper91