Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix PlainSerializer usage with std type constructor #9031

Merged
merged 3 commits into from Mar 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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}'