Skip to content

Commit

Permalink
Fix PlainSerializer usage with std type constructor (#9031)
Browse files Browse the repository at this point in the history
  • Loading branch information
sydney-runkle committed Mar 17, 2024
1 parent 1cfb22e commit 5c8afe6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
14 changes: 10 additions & 4 deletions pydantic/_internal/_typing_extra.py
Expand Up @@ -277,10 +277,16 @@ def get_function_type_hints(
"""Like `typing.get_type_hints`, but doesn't convert `X` to `Optional[X]` if the default value is `None`, also
copes with `partial`.
"""
if isinstance(function, partial):
annotations = function.func.__annotations__
else:
annotations = function.__annotations__
try:
if isinstance(function, partial):
annotations = function.func.__annotations__
else:
annotations = function.__annotations__
except AttributeError:
type_hints = get_type_hints(function)
if isinstance(function, type):
type_hints.setdefault('return', type)
return type_hints

globalns = add_module_globals(function)
type_hints = {}
Expand Down
11 changes: 11 additions & 0 deletions tests/test_serialize.py
Expand Up @@ -1171,3 +1171,14 @@ class Foo(BaseModel):

foo_recursive = Foo(items=[Foo(items=[Baz(bar_id=42, baz_id=99)])])
assert foo_recursive.model_dump() == {'items': [{'items': [{'bar_id': 42}]}]}


def test_plain_serializer_with_std_type() -> None:
"""Ensure that a plain serializer can be used with a standard type constructor, rather than having to use lambda x: std_type(x)."""

class MyModel(BaseModel):
x: Annotated[int, PlainSerializer(float)]

m = MyModel(x=1)
assert m.model_dump() == {'x': 1.0}
assert m.model_dump_json() == '{"x":1.0}'

0 comments on commit 5c8afe6

Please sign in to comment.