Skip to content

Commit 6e96b85

Browse files
authored
Expose AnySerializer via core schema (#1394)
1 parent f79d49b commit 6e96b85

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

python/pydantic_core/core_schema.py

+1
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ def field_name(self) -> str | None:
219219
'multi-host-url',
220220
'json',
221221
'uuid',
222+
'any',
222223
]
223224

224225

tests/serializers/test_any.py

+29
Original file line numberDiff line numberDiff line change
@@ -652,3 +652,32 @@ def test_ser_json_inf_nan_with_list_of_any() -> None:
652652
assert isnan(s.to_python([nan])[0])
653653
assert s.to_python([nan], mode='json')[0] is None
654654
assert s.to_json([nan]) == b'[null]'
655+
656+
657+
def test_simple_any_ser_schema_repr():
658+
assert (
659+
plain_repr(SchemaSerializer(core_schema.simple_ser_schema('any')))
660+
== 'SchemaSerializer(serializer=Any(AnySerializer),definitions=[])'
661+
)
662+
663+
664+
def test_simple_any_ser_schema():
665+
import operator
666+
667+
class MyEnum(Enum):
668+
A = (1,)
669+
B = (2,)
670+
671+
v = SchemaSerializer(
672+
core_schema.no_info_after_validator_function(
673+
operator.attrgetter('value'),
674+
core_schema.enum_schema(MyEnum, list(MyEnum.__members__.values())),
675+
serialization=core_schema.simple_ser_schema('any'),
676+
),
677+
)
678+
679+
assert v.to_python({MyEnum.A: 'x'}) == {MyEnum.A: 'x'}
680+
assert v.to_python({MyEnum.A: 'x'}, mode='json') == {'1': 'x'}
681+
assert v.to_json({MyEnum.A: 'x'}) == b'{"1":"x"}'
682+
assert v.to_python(1) == 1
683+
assert v.to_json(1) == b'1'

0 commit comments

Comments
 (0)