Skip to content

Commit 4c7c844

Browse files
authored
Support enums in format_as_xml (#3064)
1 parent 4e60e9d commit 4c7c844

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

pydantic_ai_slim/pydantic_ai/format_prompt.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from collections.abc import Iterable, Iterator, Mapping
44
from dataclasses import asdict, dataclass, field, fields, is_dataclass
55
from datetime import date
6+
from enum import Enum
67
from typing import Any, Literal
78
from xml.etree import ElementTree
89

@@ -26,8 +27,8 @@ def format_as_xml(
2627
This is useful since LLMs often find it easier to read semi-structured data (e.g. examples) as XML,
2728
rather than JSON etc.
2829
29-
Supports: `str`, `bytes`, `bytearray`, `bool`, `int`, `float`, `date`, `datetime`, `Mapping`,
30-
`Iterable`, `dataclass`, and `BaseModel`.
30+
Supports: `str`, `bytes`, `bytearray`, `bool`, `int`, `float`, `date`, `datetime`, `Enum`,
31+
`Mapping`, `Iterable`, `dataclass`, and `BaseModel`.
3132
3233
Args:
3334
obj: Python Object to serialize to XML.
@@ -101,7 +102,7 @@ def _to_xml(self, value: Any, path: str, tag: str | None = None) -> ElementTree.
101102
element.text = value
102103
elif isinstance(value, bytes | bytearray):
103104
element.text = value.decode(errors='ignore')
104-
elif isinstance(value, bool | int | float):
105+
elif isinstance(value, bool | int | float | Enum):
105106
element.text = str(value)
106107
elif isinstance(value, date):
107108
element.text = value.isoformat()

tests/test_format_as_xml.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from dataclasses import dataclass, field
44
from datetime import date, datetime
5+
from enum import Enum
56
from typing import Any
67

78
import pytest
@@ -24,6 +25,16 @@ class ExamplePydanticModel(BaseModel):
2425
age: int
2526

2627

28+
class ExampleEnum(Enum):
29+
FOO = 1
30+
BAR = 2
31+
32+
33+
class ExampleStrEnum(str, Enum):
34+
FOO = 'foo'
35+
BAR = 'bar'
36+
37+
2738
class ExamplePydanticFields(BaseModel):
2839
name: str = Field(description="The person's name")
2940
age: int = Field(description='Years', title='Age', default=18)
@@ -43,6 +54,8 @@ def location(self) -> str | None:
4354
pytest.param('a string', snapshot('<examples>a string</examples>'), id='string'),
4455
pytest.param(42, snapshot('<examples>42</examples>'), id='int'),
4556
pytest.param(None, snapshot('<examples>null</examples>'), id='null'),
57+
pytest.param(ExampleEnum.FOO, snapshot('<examples>ExampleEnum.FOO</examples>'), id='enum'),
58+
pytest.param(ExampleStrEnum.FOO, snapshot('<examples>foo</examples>'), id='str enum'),
4659
pytest.param(
4760
ExampleDataclass(name='John', age=42),
4861
snapshot("""\

0 commit comments

Comments
 (0)