Skip to content

Commit b2c4548

Browse files
Viicossydney-runkle
authored andcommitted
Use the globals of the function when evaluating the return type for PlainSerializer and WrapSerializer functions (#11008)
1 parent cb962c1 commit b2c4548

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

pydantic/functional_serializers.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,14 @@ def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaH
6363
The Pydantic core schema.
6464
"""
6565
schema = handler(source_type)
66-
globalns, localns = handler._get_types_namespace()
6766
try:
67+
# Do not pass in globals as the function could be defined in a different module.
68+
# Instead, let `get_function_return_type` infer the globals to use, but still pass
69+
# in locals that may contain a parent/rebuild namespace:
6870
return_type = _decorators.get_function_return_type(
6971
self.func,
7072
self.return_type,
71-
globalns=globalns,
72-
localns=localns,
73+
localns=handler._get_types_namespace().locals,
7374
)
7475
except NameError as e:
7576
raise PydanticUndefinedAnnotation.from_name_error(e) from e
@@ -166,11 +167,13 @@ def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaH
166167
schema = handler(source_type)
167168
globalns, localns = handler._get_types_namespace()
168169
try:
170+
# Do not pass in globals as the function could be defined in a different module.
171+
# Instead, let `get_function_return_type` infer the globals to use, but still pass
172+
# in locals that may contain a parent/rebuild namespace:
169173
return_type = _decorators.get_function_return_type(
170174
self.func,
171175
self.return_type,
172-
globalns=globalns,
173-
localns=localns,
176+
localns=handler._get_types_namespace().locals,
174177
)
175178
except NameError as e:
176179
raise PydanticUndefinedAnnotation.from_name_error(e) from e

tests/test_forward_ref.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -1314,12 +1314,22 @@ def test_uses_the_correct_globals_to_resolve_forward_refs_on_serializers(create_
13141314
# we use the globals of the underlying func to resolve the return type.
13151315
@create_module
13161316
def module_1():
1317-
from pydantic import BaseModel, field_serializer # or model_serializer, computed_field
1317+
from typing_extensions import Annotated
1318+
1319+
from pydantic import (
1320+
BaseModel,
1321+
PlainSerializer, # or WrapSerializer
1322+
field_serializer, # or model_serializer, computed_field
1323+
)
13181324

13191325
MyStr = str
13201326

1327+
def ser_func(value) -> 'MyStr':
1328+
return str(value)
1329+
13211330
class Model(BaseModel):
13221331
a: int
1332+
b: Annotated[int, PlainSerializer(ser_func)]
13231333

13241334
@field_serializer('a')
13251335
def ser(self, value) -> 'MyStr':

0 commit comments

Comments
 (0)