MCPcopy
hub / github.com/pydantic/pydantic / PlainSerializer

Class PlainSerializer

pydantic/functional_serializers.py:20–86  ·  view source on GitHub ↗

Plain serializers use a function to modify the output of serialization. This is particularly helpful when you want to customize the serialization for annotated types. Consider an input of `list`, which will be serialized into a space-delimited string. ```python from typing import A

Source from the content-addressed store, hash-verified

18
19@dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True)
20class PlainSerializer:
21 """Plain serializers use a function to modify the output of serialization.
22
23 This is particularly helpful when you want to customize the serialization for annotated types.
24 Consider an input of `list`, which will be serialized into a space-delimited string.
25
26 ```python
27 from typing import Annotated
28
29 from pydantic import BaseModel, PlainSerializer
30
31 CustomStr = Annotated[
32 list, PlainSerializer(lambda x: ' '.join(x), return_type=str)
33 ]
34
35 class StudentModel(BaseModel):
36 courses: CustomStr
37
38 student = StudentModel(courses=['Math', 'Chemistry', 'English'])
39 print(student.model_dump())
40 #> {'courses': 'Math Chemistry English'}
41 ```
42
43 Attributes:
44 func: The serializer function.
45 return_type: The return type for the function. If omitted it will be inferred from the type annotation.
46 when_used: Determines when this serializer should be used. Accepts a string with values `'always'`,
47 `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'.
48 """
49
50 func: core_schema.SerializerFunction
51 return_type: Any = PydanticUndefined
52 when_used: WhenUsed = 'always'
53
54 def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
55 """Gets the Pydantic core schema.
56
57 Args:
58 source_type: The source type.
59 handler: The `GetCoreSchemaHandler` instance.
60
61 Returns:
62 The Pydantic core schema.
63 """
64 schema = handler(source_type)
65 if self.return_type is not PydanticUndefined:
66 return_type = self.return_type
67 else:
68 try:
69 # Do not pass in globals as the function could be defined in a different module.
70 # Instead, let `get_callable_return_type` infer the globals to use, but still pass
71 # in locals that may contain a parent/rebuild namespace:
72 return_type = _decorators.get_callable_return_type(
73 self.func,
74 localns=handler._get_types_namespace().locals,
75 )
76 except NameError as e:
77 raise PydanticUndefinedAnnotation.from_name_error(e) from e

Callers 15

ModelClass · 0.90
ModelClass · 0.90
ModelClass · 0.90
ModelClass · 0.90
ModelClass · 0.90
two_xMethod · 0.90
triple_xMethod · 0.90

Calls

no outgoing calls