;iBUdZddlmZddlZddlmZmZddlmZm Z m Z m Z m Z m Z mZddlmZmZddlmZmZmZddlmZd d lmZd d lmZmZd d lmZejdRiej d diGddZ!ejdRiej d diGddZ"er9dZ#de$d<dZ%de$d< dZ&de$d< dZ'de$d< e de%Z(e de&Z)edddd dSd.Z*eddddd/dTd2Z*d3ed4dd/dUd7Z*ere e ee ge fZ+de$d8< e e ge fZ,de$d9< d:Z-de$d;< e e eee ge fZ.de$d<< e e ege fZ/de$d=< d>Z0de$d?< d@Z1de$dA<e dBe-Z2e dCe0Z3edVdEZ4ed4ddFdWdHZ4edd4ddIdXdKZ4 dYd3d4edIdZdNZ4e dOZ5er e e5dfZ6dSejdRiej GdPdQZ6dS)[zEThis module contains related classes and functions for serialization.) annotationsN)partial partialmethod) TYPE_CHECKING AnnotatedAnyCallableLiteralTypeVaroverload)PydanticUndefined core_schema)SerializationInfoSerializerFunctionWrapHandlerWhenUsed) TypeAlias)PydanticUndefinedAnnotation) _decorators_internal_dataclass)GetCoreSchemaHandlerfrozenTcBeZdZUdZded<eZded<dZded<ddZdS)PlainSerializeraPlain 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 Annotated from pydantic import BaseModel, PlainSerializer CustomStr = Annotated[ list, PlainSerializer(lambda x: ' '.join(x), return_type=str) ] class StudentModel(BaseModel): courses: CustomStr student = StudentModel(courses=['Math', 'Chemistry', 'English']) print(student.model_dump()) #> {'courses': 'Math Chemistry English'} ``` Attributes: func: The serializer function. return_type: The return type for the function. If omitted it will be inferred from the type annotation. when_used: Determines when this serializer should be used. Accepts a string with values `'always'`, `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'. zcore_schema.SerializerFunctionfuncr return_typealwaysr when_used source_typehandlerrreturncore_schema.CoreSchemac||}|jtur|j}n[ tj|j|j}n'#t$r}tj ||d}~wwxYw|turdn| |}tj |jtj |jd||j|d<|S)zGets the Pydantic core schema. Args: source_type: The source type. handler: The `GetCoreSchemaHandler` instance. Returns: The Pydantic core schema. localnsNplainfunctioninfo_arg return_schemar serialization)rr rget_callable_return_typer_get_types_namespacelocals NameErrorrfrom_name_errorgenerate_schemar$plain_serializer_function_ser_schemainspect_annotated_serializerrselfrr schemarer*s SC:\PYTHON\MyICR_Workspace\venv\Lib\site-packages\pydantic/functional_serializers.py__get_pydantic_core_schema__z,PlainSerializer.__get_pydantic_core_schema__5s%%  #4 4 4*KK L*BI#88::A  L L L1A!DD!K L!,/@ @ @gF]F]^iFjFj "-"RY =diQQ'n # # #   2A A: A55A:Nrrr rr!r" __name__ __module__ __qualname____doc____annotations__r rrr9r8rrsd:)((((K(((("I""""      rCrcBeZdZUdZded<eZded<dZded<ddZdS)WrapSerializeraWrap serializers receive the raw inputs along with a handler function that applies the standard serialization logic, and can modify the resulting value before returning it as the final output of serialization. For example, here's a scenario in which a wrap serializer transforms timezones to UTC **and** utilizes the existing `datetime` serialization logic. ```python from datetime import datetime, timezone from typing import Annotated, Any from pydantic import BaseModel, WrapSerializer class EventDatetime(BaseModel): start: datetime end: datetime def convert_to_utc(value: Any, handler, info) -> dict[str, datetime]: # Note that `handler` can actually help serialize the `value` for # further custom serialization in case it's a subclass. partial_result = handler(value, info) if info.mode == 'json': return { k: datetime.fromisoformat(v).astimezone(timezone.utc) for k, v in partial_result.items() } return {k: v.astimezone(timezone.utc) for k, v in partial_result.items()} UTCEventDatetime = Annotated[EventDatetime, WrapSerializer(convert_to_utc)] class EventModel(BaseModel): event_datetime: UTCEventDatetime dt = EventDatetime( start='2024-01-01T07:00:00-08:00', end='2024-01-03T20:00:00+06:00' ) event = EventModel(event_datetime=dt) print(event.model_dump()) ''' { 'event_datetime': { 'start': datetime.datetime( 2024, 1, 1, 15, 0, tzinfo=datetime.timezone.utc ), 'end': datetime.datetime( 2024, 1, 3, 14, 0, tzinfo=datetime.timezone.utc ), } } ''' print(event.model_dump_json()) ''' {"event_datetime":{"start":"2024-01-01T15:00:00Z","end":"2024-01-03T14:00:00Z"}} ''' ``` Attributes: func: The serializer function to be wrapped. return_type: The return type for the function. If omitted it will be inferred from the type annotation. when_used: Determines when this serializer should be used. Accepts a string with values `'always'`, `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'. z"core_schema.WrapSerializerFunctionrrrrrrrr rr!r"c||}|jtur|j}n[ tj|j|j}n'#t$r}tj ||d}~wwxYw|turdn| |}tj |jtj |jd||j|d<|S)zThis method is used to get the Pydantic core schema of the class. Args: source_type: Source type. handler: Core schema handler. Returns: The generated core schema of the class. r$Nwrapr'r+)rr rr,rr-r.r/rr0r1r#wrap_serializer_function_ser_schemar3rr4s r8r9z+WrapSerializer.__get_pydantic_core_schema__s%%  #4 4 4*KK L*BI#88::A  L L L1A!DD!K L!,/@ @ @gF]F]^iFjFj "-"QY =diPP'n # # #   r:Nr;r<rBrCr8rErEXse<<|-,,,(K(((("I""""      rCrEz!partial[Any] | partialmethod[Any]r_Partialz)core_schema.SerializerFunction | _PartialFieldPlainSerializerz-core_schema.WrapSerializerFunction | _PartialFieldWrapSerializerz*FieldPlainSerializer | FieldWrapSerializerFieldSerializer_FieldPlainSerializerT)bound_FieldWrapSerializerT.)rr check_fieldsfieldstrfieldsmodeLiteral['wrap']rrrrrP bool | Noner!8Callable[[_FieldWrapSerializerT], _FieldWrapSerializerT]cdSNrBrQrTrrrPrSs r8field_serializerr[s @CsrC)rTrrrPLiteral['plain']:Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]cdSrYrBrZs r8r[r[s BErCr&rLiteral['plain', 'wrap']uCallable[[_FieldWrapSerializerT], _FieldWrapSerializerT] | Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT]c$dfd }|S)aDecorator that enables custom field serialization. In the below example, a field of type `set` is used to mitigate duplication. A `field_serializer` is used to serialize the data as a sorted list. ```python from pydantic import BaseModel, field_serializer class StudentModel(BaseModel): name: str = 'Jane' courses: set[str] @field_serializer('courses', when_used='json') def serialize_courses_in_order(self, courses: set[str]): return sorted(courses) student = StudentModel(courses={'Math', 'Chemistry', 'English'}) print(student.model_dump_json()) #> {"name":"Jane","courses":["Chemistry","English","Math"]} ``` See [the usage documentation](../concepts/serialization.md#serializers) for more information. Four signatures are supported: - `(self, value: Any, info: FieldSerializationInfo)` - `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)` - `(value: Any, info: SerializationInfo)` - `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)` Args: fields: Which field(s) the method should be called on. mode: The serialization mode. - `plain` means the function will be called instead of the default serialization logic, - `wrap` means the function will be called with an argument to optionally call the default serialization logic. return_type: Optional return type for the function, if omitted it will be inferred from the type annotation. when_used: Determines the serializer will be used for serialization. check_fields: Whether to check that the fields actually exist on the model. Returns: The decorator function. frLr!(_decorators.PydanticDescriptorProxy[Any]c`tj}tj||S)N)rSrTrrrP)rFieldSerializerDecoratorInfoPydanticDescriptorProxy)rbdec_inforPrSrTrrs r8deczfield_serializer..decs>;#%    21h???rC)rbrLr!rcrB)rTrrrPrSrhs````` r8r[r[sKn@@@@@@@@@@ JrCModelPlainSerializerWithInfoModelPlainSerializerWithoutInfoz>ModelPlainSerializerWithInfo | ModelPlainSerializerWithoutInfoModelPlainSerializerModelWrapSerializerWithInfoModelWrapSerializerWithoutInfoz {'unit': 'C', 'value': 100} ``` Two signatures are supported for `mode='plain'`, which is the default: - `(self)` - `(self, info: SerializationInfo)` And two other signatures for `mode='wrap'`: - `(self, nxt: SerializerFunctionWrapHandler)` - `(self, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)` See [the usage documentation](../concepts/serialization.md#serializers) for more information. Args: f: The function to be decorated. mode: The serialization mode. - `'plain'` means the function will be called instead of the default serialization logic - `'wrap'` means the function will be called with an argument to optionally call the default serialization logic. when_used: Determines when this serializer should be used. return_type: The return type for the function. If omitted it will be inferred from the type annotation. Returns: The decorator function. rbror!rcc\tj}tj||S)N)rTrr)rModelSerializerDecoratorInforf)rbrgrTrrs r8rhzmodel_serializer..decs/;S^jsttt21h???rCN)rbror!rcrB)rbrTrrrhs ``` r8rsrsYsO@@@@@@@@@ y s1vv rCAnyTypec0eZdZdZd dZd d ZejZd S)SerializeAsAnyzAnnotation used to mark a type as having duck-typing serialization behavior. See [usage documentation](../concepts/serialization.md#serializing-with-duck-typing) for more details. itemrr!c8t|tfSrY)rr)clsrs r8__class_getitem__z SerializeAsAny.__class_getitem__sT>#3#334 4rCrr rr"c||}|}|ddkr(|}|d}|ddk(tjd|d<|S)Ntype definitionsr6anyr+)copyrsimple_ser_schema)r5rr r6schema_to_updates r8r9z+SerializeAsAny.__get_pydantic_core_schema__suW[))F% "6*m;;#3#8#8#:#: #3H#= #6*m;;1<0Me0T0T _ -MrCN)rrr!rr;)r=r>r?r@rr9object__hash__rBrCr8rrsI   5 5 5 5    ?rCrrB)rQrRrSrRrTrUrrrrrPrVr!rW)rQrRrSrRrTr\rrrrrPrVr!r]) rSrRrTr_rrrrrPrVr!r`)rbrpr!rp)rTrUrrrrr!rt)rTr\rrrrr!rwrY) rbryrTr_rrrrr!rz)7r@ __future__r dataclasses functoolsrrtypingrrrr r r r pydantic_corer rpydantic_core.core_schemarrrtyping_extensionsrr _internalrrannotated_handlersr dataclass slots_truerrErIrArJrKrLrMrOr[rirjrkrlrmrnrorprqrsr~rrBrCr8rsYKKK"""""",,,,,,,,VVVVVVVVVVVVVVVVVV88888888``````````''''''))))))77777777444444EE,7EEEEEBBBBBBBFEBJEE,7EEEEEcccccccFEcL X=H====&QQQQQ@%TTTTT?!MOMMMM0$W%=EYZZZ#G$;CVWWW  #CCCCC C ! #EEEEE E&-(" $ AAAAAAHX/7=Ns=S7TVY7Y.Z ZZZZN193%*1E#EEEEQ&fffff4-5s