Skip to content

Commit

Permalink
Expose AnySerializer via core schema (#1394)
Browse files Browse the repository at this point in the history
  • Loading branch information
BoxyUwU authored Aug 6, 2024
1 parent f79d49b commit 6e96b85
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions python/pydantic_core/core_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ def field_name(self) -> str | None:
'multi-host-url',
'json',
'uuid',
'any',
]


Expand Down
29 changes: 29 additions & 0 deletions tests/serializers/test_any.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,3 +652,32 @@ def test_ser_json_inf_nan_with_list_of_any() -> None:
assert isnan(s.to_python([nan])[0])
assert s.to_python([nan], mode='json')[0] is None
assert s.to_json([nan]) == b'[null]'


def test_simple_any_ser_schema_repr():
assert (
plain_repr(SchemaSerializer(core_schema.simple_ser_schema('any')))
== 'SchemaSerializer(serializer=Any(AnySerializer),definitions=[])'
)


def test_simple_any_ser_schema():
import operator

class MyEnum(Enum):
A = (1,)
B = (2,)

v = SchemaSerializer(
core_schema.no_info_after_validator_function(
operator.attrgetter('value'),
core_schema.enum_schema(MyEnum, list(MyEnum.__members__.values())),
serialization=core_schema.simple_ser_schema('any'),
),
)

assert v.to_python({MyEnum.A: 'x'}) == {MyEnum.A: 'x'}
assert v.to_python({MyEnum.A: 'x'}, mode='json') == {'1': 'x'}
assert v.to_json({MyEnum.A: 'x'}) == b'{"1":"x"}'
assert v.to_python(1) == 1
assert v.to_json(1) == b'1'

0 comments on commit 6e96b85

Please sign in to comment.