XjFPUdZddlmZddlZddlmZmZddlmZm Z m Z m Z m Z m Z mZddlmZmZddlmZmZmZddlmZd d lmZd d lmZmZd d lmZd d lm Z ejBd=iejDddiGddZ#ejBd=iejDddiGddZ$er3dZ%de&d<dZ'de&d< dZ(de&d< dZ)de&d< e de'Z*e de(Z+ed d d d! d>d"Z,ed d d d d# d?d$Z,d%ed&dd# d@d'Z,erme e ee ge fZ-de&d(< e e ge fZ.de&d)< d*Z/de&d+< e e eee ge fZ0de&d,< e e ege fZ1de&d-< d.Z2de&d/< d0Z3de&d1<e d2e/Z4e d3e2Z5edAd4Z6ed&d d5 dBd6Z6ed d&d d7 dCd8Z6 dDd%d&ed7 dEd9Z6e d:Z7ere e7d fZ8yejBd=iejDGd;d<Z8y)FzEThis module contains related classes and functions for serialization.) annotationsN)partial partialmethod) TYPE_CHECKING AnnotatedAnyCallableLiteralTypeVaroverload)PydanticUndefined core_schema)SerializationInfoSerializerFunctionWrapHandlerWhenUsed) TypeAlias)PydanticUndefinedAnnotation) _decorators_internal_dataclass)GetCoreSchemaHandler)PydanticUserErrorfrozenTc@eZdZUdZded<eZded<dZded<d d Zy ) 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_usedc||}|jtur |j}n: tj|j|j j }|turdn|j|}tj|jtj|jd||j|d<|S#t$r}tj||d}~wwxYw)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_serializerrself source_typehandlerschemarer's s/mnt/ssd/data/Dropbox/adrian/vault-secondbrain/venv/lib/python3.12/site-packages/pydantic/functional_serializers.py__get_pydantic_core_schema__z,PlainSerializer.__get_pydantic_core_schema__6s%   #4 4**K L*BBII#88:AA !,/@ @gF]F]^iFj "-"R"RYY ==diiQ'nn #    L1AA!D!K L9C C1C,,C1Nr3rr4rreturnzcore_schema.CoreSchema __name__ __module__ __qualname____doc____annotations__r rrr8r7rrs(: )((K("Ix" rCrc@eZdZUdZded<eZded<dZded<d d Zy ) 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.WrapSerializerFunctionrrrrrrc||}|jtur |j}n: tj|j|j j }|turdn|j|}tj|jtj|jd||j|d<|S#t$r}tj||d}~wwxYw)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,rr-r.r#wrap_serializer_function_ser_schemar0rr1s r7r8z+WrapSerializer.__get_pydantic_core_schema__s%   #4 4**K L*BBII#88:AA !,/@ @gF]F]^iFj "-"Q"QYY ==diiP'nn #    L1AA!D!K Lr9Nr:r<rBrCr7rErEYs)<| -,(K("Ix" rCrEz!partial[Any] | partialmethod[Any]r_Partialz)core_schema.SerializerFunction | _PartialFieldPlainSerializerz-core_schema.WrapSerializerFunction | _PartialFieldWrapSerializerz*FieldPlainSerializer | FieldWrapSerializerFieldSerializer_FieldPlainSerializerT)bound_FieldWrapSerializerT.)rr check_fieldscyNrBfieldmoderrrPfieldss r7field_serializerrWs @CrC)rUrrrPcyrRrBrSs r7rWrWs BErCr#rct|st|tr tdd|gt dDs tdddfd }|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 for the decorated serializer: - `(self, value: Any, info: FieldSerializationInfo)` - `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)` - `(value: Any, info: SerializationInfo)` - `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)` Args: *fields: The field names the serializer should apply to. 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. Raises: PydanticUserError: - If the decorator is used without any arguments (at least one field name must be provided). - If the provided field names are not strings. zThe `@field_serializer` decorator cannot be used without arguments, at least one field must be provided. For example: `@field_serializer('', ...)`.zdecorator-missing-arguments)codec3<K|]}t|tywrR) isinstancestr).0rTs r7 z#field_serializer..*s:%z%%:szThe provided field names to the `@field_serializer` decorator should be strings. For example: `@field_serializer('', '', ...).`zdecorator-invalid-fieldscdtj}tj||S)N)rVrUrrrP)rFieldSerializerDecoratorInfoPydanticDescriptorProxy)fdec_inforPrVrUrrs r7deczfield_serializer..dec1s7;;#%  221h??rC)rcrLr;(_decorators.PydanticDescriptorProxy[Any])callabler\ classmethodrall)rTrUrrrPrVres ````` r7rWrWspt*UK8 E.  ^V^F :6: : Y+  @@ 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. c`tj}tj||S)N)rUrr)rModelSerializerDecoratorInforb)rcrdrUrrs r7rezmodel_serializer..decs,;;S^jst221h??rC)rcrpr;rfrB)rcrUrrres ``` r7rtrtls@@ y 1v rCAnyTypecDeZdZdZddZ ddZejZy)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. c(t|tfSrR)rr})clsitems r7__class_getitem__z SerializeAsAny.__class_getitem__sT>#334 4rCc||}|}|ddk(r|j}|d}|ddk(rtjd|d<|S)Ntype definitionsr5anyr()copyrsimple_ser_schema)r2r3r4r5schema_to_updates r7r8z+SerializeAsAny.__get_pydantic_core_schema__sg[)F% "6*m;#3#8#8#: #3H#= #6*m;1<0M0Me0T _ -MrCN)rrr;rr:)r=r>r?r@rr8object__hash__rBrCr7r}r}s4  5 " -A  # ??rCr}rB)rTr]rVr]rULiteral['wrap']rrrrrP bool | Noner;z8Callable[[_FieldWrapSerializerT], _FieldWrapSerializerT])rTr]rVr]rULiteral['plain']rrrrrPrr;z:Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT])rTr]rVr]rULiteral['plain', 'wrap']rrrrrPrr;zuCallable[[_FieldWrapSerializerT], _FieldWrapSerializerT] | Callable[[_FieldPlainSerializerT], _FieldPlainSerializerT])rcrqr;rq)rUrrrrrr;z8Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT])rUrrrrrr;z:Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT]rR) rcz5_ModelPlainSerializerT | _ModelWrapSerializerT | NonerUrrrrrr;z_ModelPlainSerializerT | Callable[[_ModelWrapSerializerT], _ModelWrapSerializerT] | Callable[[_ModelPlainSerializerT], _ModelPlainSerializerT])9r@ __future__r dataclasses functoolsrrtypingrrrr r r r pydantic_corer rpydantic_core.core_schemarrrtyping_extensionsrr _internalrrannotated_handlersrerrorsr dataclass slots_truerrErIrArJrKrLrMrOrWrjrkrlrmrnrorprqrrrtr{r}rBrCr7rsMK",VVV8``')74%E,77EEBBFBJE,77EEccFcL=Hi=&Q)Q@%TT?!MOYM0$%=EYZ#$;CVW  #C CC  C  C  CC>C C ! #E EE  E  E  EE@E E&-(" $S SS # S  SSSASl/7=Ns=S7TVY7Y.Z )ZN193%*1E#YEQ&f)f4-5s