fG$UdZddlmZddlZddlZddlZddlZddlmZddlm Z ddl m Z ddlm Z mZddlmZddlZddlZdd lmZdd lmZmZmZmZd d lmZd d lmZmZmZmZm Z m!Z!m"Z"d dl#m$Z$m%Z%d dl&m'Z'd dl(m)Z)d dlm*Z*ejVrd dl,m-Z-ne*Z.dZ/eZ0de1d<ejddk\rddlZej0ezZ3de1d<neZ3de1d<GddejhdZ5Gdde5dZ6Gdd e jnZ8Gd!d"ejhZ9id#d$d%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1dd2d3d4dd5dddddddddddddddd6Z:efe0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0d7" dFd9Z e;ejxe jzZ>e>jd8Gd:d;e jnZ@efddd< dGd=ZAejdHiejGd>d?ZDdId@ZEejdAZGejddddddddd3edB dJdCZIejdKdDZI dLdddddddddedB dMdEZIy)NzDefining fields on models.) annotationsN)copy)Field)cached_property)AnyClassVar)warn)PydanticUndefined)Literal TypeAliasUnpack deprecated)types) _decorators_fields _generics_internal_dataclass_repr _typing_extra_utils) AliasChoices AliasPath)JsonDict)PydanticUserError)PydanticDeprecatedSince20)ReprArgs)r PrivateAttrcomputed_fieldr_Unset) r DeprecatedcpeZdZUdZded<ded<ded<ded <d ed <ded <ded <ded<ded<ded<ded<ded<ded<ded<ded<ded<ded<ded <ded!<d"ed#<ded$<ded%<ded&<d'ed(<d)ed*<d+ed,<d-ed.<ded/<ded0<d1ed2<ded3<ded4<ded5<ded6<ded7<y8)9_FromFieldInfoInputsz[This class exists solely to add type checking for the `**kwargs` in `FieldInfo.from_field`.type[Any] | None annotationtyping.Callable[[], Any] | Nonedefault_factory str | Nonealias int | Nonealias_priority%str | AliasPath | AliasChoices | Nonevalidation_aliasserialization_aliastitle8typing_extensions.Callable[[str, FieldInfo], str] | Nonefield_title_generator descriptionlist[Any] | Noneexamples bool | Noneexclude!annotated_types.SupportsGt | Nonegt!annotated_types.SupportsGe | Nonege!annotated_types.SupportsLt | Nonelt!annotated_types.SupportsLe | Nonele float | None multiple_ofstrict min_length max_length str | typing.Pattern[str] | Nonepattern allow_inf_nan max_digitsdecimal_placesz(Literal['smart', 'left_to_right'] | None union_mode str | types.Discriminator | None discriminatorDeprecated | str | bool | Noner3JsonDict | typing.Callable[[JsonDict], None] | Nonejson_schema_extrafrozenvalidate_defaultboolreprinitinit_varkw_onlycoerce_numbers_to_str fail_fastN__name__ __module__ __qualname____doc____annotations__X/var/lib/jenkins/workspace/mettalog/venv/lib/python3.12/site-packages/pydantic/fields.pyr%r%/se  44 ;;## SS ))))))))  --8833..JJ !! J  &&rar%F)totalceZdZUdZded<y)_FieldInfoInputszYThis class exists solely to add type checking for the `**kwargs` in `FieldInfo.__init__`.rdefaultNrZr`rarbrereWs c LrareceZdZUdZded<ded<ded<ded <d ed <d ed <ded<ded<ded<ded<ded<ded<ded<ded<ded<ded<ded<ded <ded!<ded"<ded#<d$ed%<d&Zejejejejejejejejd'd'd'd'd'd'ej d(Zd)ed*<d;d+Zeefdd.Zed?d/Zed@d0ZedAd1ZedBd2ZedCd3Zd4d5dDd6ZdEd7ZdFd8Z dGd9Z!dHd:Z"y')I FieldInfoaEThis class holds information about a field. `FieldInfo` is used for any field definition regardless of whether the [`Field()`][pydantic.fields.Field] function is explicitly used. !!! warning You generally shouldn't be creating `FieldInfo` directly, you'll only need to use it when accessing [`BaseModel`][pydantic.main.BaseModel] `.model_fields` internals. Attributes: annotation: The type annotation of the field. default: The default value of the field. default_factory: The factory function used to construct the default for the field. alias: The alias name of the field. alias_priority: The priority of the field's alias. validation_alias: The validation alias of the field. serialization_alias: The serialization alias of the field. title: The title of the field. field_title_generator: A callable that takes a field name and returns title for it. description: The description of the field. examples: List of examples of the field. exclude: Whether to exclude the field from the model serialization. discriminator: Field name or Discriminator for discriminating the type in a tagged union. deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. json_schema_extra: A dict or callable to provide extra JSON schema properties. frozen: Whether the field is frozen. validate_default: Whether to validate the default value of the field. repr: Whether to include the field in representation of the model. init: Whether the field should be included in the constructor of the dataclass. init_var: Whether the field should _only_ be included in the constructor of the dataclass, and not stored. kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass. metadata: List of metadata constraints. r&r'rrfr(r)r*r+r,r-r.r/r0r1z-typing.Callable[[str, FieldInfo], str] | Noner3r4r5r6r7r8rLrMrNrrOrPrQrRrSrTrUrVrW list[Any]metadata)r'rfr)r+r-r/r0r1r3r4r6r8rMrrPrQrRrTrUrVrWrj_attributes_setN)rCr:r<r>r@rBrDrErGrHrIrJrKrXrYz7ClassVar[dict[str, typing.Callable[[Any], Any] | None]]metadata_lookupc ,|jDcic]\}}|tus||c}}|_|jDcic]%\}}||turtj |n|'}}}|j |j d\|_}|jdt}|tur t|_ n||_ |jdd|_ |jtur|j td|jdd|_ |jdd|_|jdd|_t!d |j|j|jfD}|r|jd dxsd nd|_|jd d|_|jd d|_|jdd|_|jdd|_|jdd|_|jdd|_|jdt1|dd|_|jdd|_|jdd|_|jdd|_|jdd|_|jdd|_|jdd|_|jdd|_ |jC||z|_"ycc}}wcc}}w)aThis class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function or one of the constructor classmethods. See the signature of `pydantic.fields.Field` for more details about the expected arguments. r'rfr)N/cannot specify both default and default_factoryr+r/r0c3$K|]}|du ywNr`).0r+s rb z%FieldInfo.__init__..sx5,xsr-r1r3r4r6r8rMrrTTrPrRrQrUrVrW)#itemsr rk_DefaultValuesget_extract_metadatar'popr Ellipsisrfr) TypeErrorr+r/r0anyr-r1r3r4r6r8rMgetattrrrTrPrRrQrUrVrW_collect_metadatarj)selfkwargskvannotation_metadatarf alias_is_sets rb__init__zFieldInfo.__init__s 28SA1F?1SMS\\^\TQ!a6k^''*q@\\/3/E/EfjjQ]F^/_,,**Y(9: h ,DL"DL%zz*;TB <<0 0T5I5I5UMN NZZ. & +=t D#)::.CT#J x4::tG\G\^b^v^v:wxx IUfjj)94@EA[_ZZ. %+ZZ0G%N"!::mT: :t4 zz)T2 #ZZ> **\74t3TUJJvt, !',?!F & +=t Djj40 JJvt,  :t4 zz)T2 ..v69LL K T\sL L *Lc :d|vr tdtdd|i|S)a~Create a new `FieldInfo` object with the `Field` function. Args: default: The default value for the field. Defaults to Undefined. **kwargs: Additional arguments dictionary. Raises: TypeError: If 'annotation' is passed as a keyword argument. Returns: A new FieldInfo object with the given parameters. Example: This is how you can create a field with default value like this: ```python import pydantic class MyModel(pydantic.BaseModel): foo: int = pydantic.Field(4) ``` r'z9"annotation" is not permitted as a Field keyword argumentrfr`)rzrh)rfrs rb from_fieldzFieldInfo.from_fields+0 6 !WX X33F33racd}tj|r,d}|tjurtj|d}tj |rtj|^}}tj|rd}|Dcgc]}t |ts|}}tj|d|i}|rt|}||_ |xs |j|_ g}|D]f}tj|r|j|_*t |ts|j|L|j!|j"h||_|St||xsdScc}w)aCreates a `FieldInfo` instance from a bare annotation. This function is used internally to create a `FieldInfo` from a bare annotation like this: ```python import pydantic class MyModel(pydantic.BaseModel): foo: int # <-- like this ``` We also account for the case where the annotation can be an instance of `Annotated` and where one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.: ```python import annotated_types from typing_extensions import Annotated import pydantic class MyModel(pydantic.BaseModel): foo: Annotated[int, annotated_types.Gt(42)] bar: Annotated[int, pydantic.Field(gt=42)] ``` Args: annotation: An annotation object. Returns: An instance of the field metadata. FTrr'N)r'rQ)r is_finalvartyping_extensionsFinalget_args is_annotated isinstancerhmerge_field_infosrr'rQis_deprecated_instancemessagerappendextendrj) r'final first_arg extra_argsafield_info_annotations field_infonew_field_inforjs rbfrom_annotationzFieldInfo.from_annotationsIB  $ $Z 0E!2!8!88.77 CAF  % %j 1%6%?%? %K "I ((31;%XAz!Y?Wa%X "%X"446LcYbcJ!%j!1,5)(-(B1B1B%&(#A$;;A>45II1'95 *  3 $+3'%%Ju}EE#&Ys E-"E-c L||ur tddtj|}|r*|tjurtj |d}t |trtj|\|_ }|xj|z c_ |jg|Dcgc]}t |ts|c}|d|ji}|xs |j|_ |St |tjr&d}|tjur!d}t!j"t$t$}n(t |tjrd}|j&}tj)|}tj|\|_ }|xj|z c_ |jg|Dcgc]}t |ts|c}|d|ji}|xs |j|_ ||_t-|dd |_t-|d d |_|Stj2|rtj |^}}|D cgc]} t | ts| } } tj| ||d } g} |D]f} tj4| r| j6| _*t | ts| j;| L| j=| jh| | _ | St|||xsd Scc}wcc}wcc} w) aCreate `FieldInfo` from an annotation with a default value. This is used in cases like the following: ```python import annotated_types from typing_extensions import Annotated import pydantic class MyModel(pydantic.BaseModel): foo: int = 4 # <-- like this bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this ``` Args: annotation: The type annotation of the field. default: The default value of the field. Returns: A field object with the passed values. zError when building FieldInfo from annotated attribute. Make sure you don't have any field name clashing with a type annotation zunevaluable-type-annotationcoderr'FTrUNrW)r'rf)r'rfrQ)rrrrrrrrhrwr'rjrrQ dataclassesrInitVartypingcastrtype_from_dataclass_fieldrVr|rUrWrrrrrr) r'rfrrxrVpydantic_fieldrrr field_infosrrjs rbfrom_annotated_attributez"FieldInfo.from_annotated_attributeMs2  #[2  ))*5 Z'8'>'>>*33J?BJ gy )6?6Q6QR\6] 3G  3    3 3 /g//0MJq)4L!MOVcjcucuG#4gnnGNN g{00 1H[000#[[c2 J (;(;<'__ &<N $2$6$67J$K!-E-I-IJ]_a-b*8$?JO`bfDgDwGaDwevDw,-@AEV,-@A % + +N ;((!!Y/()HT!W%)%&, !'' 2:!9: "8??#45   s6AF FFcR|j}|tjurt}|jtjurt}n |j}|j j Dcic]\}}|tvs||}}}td|||jd|Scc}}w)a]Return a new `FieldInfo` instance from a `dataclasses.Field` instance. Args: dc_field: The `dataclasses.Field` instance to convert. Returns: The corresponding `FieldInfo` instance. Raises: TypeError: If any of the `FieldInfo` kwargs does not match the `dataclass.Field` kwargs. )rfr)rTr`) rfrMISSINGr r)rjrt_FIELD_ARG_NAMESrrT)dc_fieldrfr)rrdc_field_metadatas rbrzFieldInfo._from_dataclass_fields"" k)) )G  # #{':': :?EO&66O/7.?.?.E.E.Gada1P`K`QTaaoWoHMMo]noobs 1B#B#c|9tj|r$tj|^}}|t |fS|gfS)a/Tries to extract metadata/constraints from an annotation if it uses `Annotated`. Args: annotation: The type hint annotation for which metadata has to be extracted. Returns: A tuple containing the extracted metadata type and the list of extra arguments. )rrrrr)r'rrs rbrwzFieldInfo._extract_metadatasG  !))*5):)C)CJ)O& J $z"2222~rac,g}i}t|jD]>\}} tj|}||=| ||||<(|j ||@|r$|j t jdi||S#t$rYtwxYw)a Collect annotations from kwargs. Args: kwargs: Keyword arguments passed to the function. Returns: A list of metadata objects - a combination of `annotated_types.BaseMetadata` and `PydanticMetadata`. r`)rrtrhrlrrrpydantic_general_metadata)rrjgeneral_metadatakeyvaluemarkers rbr}zFieldInfo._collect_metadatas!v||~.JC "2237s  >,1$S)OOF5M2/  OOG==Q@PQ R  sB BBc|jyt|jtr|jrdSdSt|jtr |jS|jjSzr@rBrHrIrJrDrErX)"r)r+r-r/r0r1r3r4r6r8rMrrPrQrRrTrUrVrWrGrCrXr:r<r>r@rBrHrIrJrDrErKrYextrac" T|#jdd}$|$ tdd|#jdd}%|%tdt|dtfvr|%}|#jdd}&|&td t| dtfvr|&} |#jd d}'|' td d|#jd d}(|(td t|(durd}|#jdd})|) tdd|#rDtddj d|#j Ddt| r| tur|#} |r.|tur&t|tttfs td|tdfvrt|tr|}|tdfvr|}|#jdd}*|*tdttj|fid|d|d|d|d|d|d|d |d!| d"| d#| d$| d%| d&|d'|d(|d)|d*|d+|d,|d-|d.|d/|d0|d1|d2|d3|d4|d5| d6|d7|d8|d9|!d:|"S);aeUsage docs: https://docs.pydantic.dev/2.9/concepts/fields Create a field for objects that can be configured. Used to provide extra information about a field, either for the model schema or complex validation. Some arguments apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`. Note: - Any `_Unset` objects will be replaced by the corresponding value defined in the `_DefaultValues` dictionary. If a key for the `_Unset` object is not found in the `_DefaultValues` dictionary, it will default to `None` Args: default: Default value if the field is not set. default_factory: A callable to generate the default value, such as :func:`~datetime.utcnow`. alias: The name to use for the attribute when validating or serializing by alias. This is often used for things like converting between snake and camel case. alias_priority: Priority of the alias. This affects whether an alias generator is used. validation_alias: Like `alias`, but only affects validation, not serialization. serialization_alias: Like `alias`, but only affects serialization, not validation. title: Human-readable title. field_title_generator: A callable that takes a field name and returns title for it. description: Human-readable description. examples: Example values for this field. exclude: Whether to exclude the field from the model serialization. discriminator: Field name or Discriminator for discriminating the type in a tagged union. deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. json_schema_extra: A dict or callable to provide extra JSON schema properties. frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error. validate_default: If `True`, apply validation to the default value every time you create an instance. Otherwise, for performance reasons, the default value of the field is trusted and not validated. repr: A boolean indicating whether to include the field in the `__repr__` output. init: Whether the field should be included in the constructor of the dataclass. (Only applies to dataclasses.) init_var: Whether the field should _only_ be included in the constructor of the dataclass. (Only applies to dataclasses.) kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass. (Only applies to dataclasses.) coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode). strict: If `True`, strict validation is applied to the field. See [Strict Mode](../concepts/strict_mode.md) for details. gt: Greater than. If set, value must be greater than this. Only applicable to numbers. ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. lt: Less than. If set, value must be less than this. Only applicable to numbers. le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. multiple_of: Value must be a multiple of this. Only applicable to numbers. min_length: Minimum length for iterables. max_length: Maximum length for iterables. pattern: Pattern for strings (a regular expression). allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to numbers. max_digits: Maximum number of allow digits for strings. decimal_places: Maximum number of decimal places allowed for numbers. union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`. See [Union Mode](../concepts/unions.md#union-modes) for details. fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected. This option can be applied only to iterable types (list, tuple, set, and frozenset). extra: (Deprecated) Extra fields that will be included in the JSON schema. !!! warning Deprecated The `extra` kwargs is deprecated. Use `json_schema_extra` instead. Returns: A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on type-annotated fields without causing a type error. constNz)`const` is removed, use `Literal` insteadzremoved-kwargsr min_itemszG`min_items` is deprecated and will be removed, use `min_length` instead max_itemszG`max_items` is deprecated and will be removed, use `max_length` instead unique_itemsz`unique_items` is removed, use `Set` instead(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)allow_mutationzH`allow_mutation` is deprecated and will be removed. use `frozen` insteadFTregexz)`regex` is removed. use `pattern` insteadzzUsing extra keyword arguments on `Field` is deprecated and will be removed. Use `json_schema_extra` instead. (Extra keys: z, c3<K|]}|jywrp)__repr__)rqrs rbrrzField..=s&Jqzz|&Js)zSInvalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`includezS`include` is deprecated and does nothing. It will be removed, use `exclude` insteadr)r+r-r/r0r1r3r4r6r8rMrrPrQrGrRrTrUrVrWrXrCr:r<r>r@rBrDrErHrIrJrKrY)rxrr DeprecationWarningr joinkeysrrrrrzrhr)+rfr)r+r-r/r0r1r3r4r6r8rMrrPrQrRrTrUrVrWrGrCrXr:r<r>r@rBrHrIrJrDrErKrYrrrrrrrrs+ rbrrsJP IIgt $E  KRbcc +t,I VXjk $ '"J +t,I VXjk $ '"J99^T2Lf"   YY/6N! WYkl U "F IIgt $E  KRbcc   !YY&JUZZ\&JJK1 N   !$5$? %   F *+c<-KLmnnvtn,E31G#FD>) ii 4(G bdvw   $ '$ $ & $  * $  0 $ $ 4$  $ $ $ $$ $ ,$ $  !$ "*#$ $%$ &'$ ()$ *+$ ,4-$ ./$ 0 1$ 2 3$ 4 5$ 6 7$ 8 9$ :;$ <=$ >$?$ @A$ B&C$ DE$ FG$ $racheZdZdZdZefdd d dZejsd dZ d dZ d dZ dd Z y)ModelPrivateAttraA descriptor for private attributes in class models. !!! warning You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use `pydantic.fields.PrivateAttr`. (This is similar to `FieldInfo` vs. `Field`.) Attributes: default: The default value of the attribute if not provided. default_factory: A callable function that generates the default value of the attribute if not provided. rfr)Nr)c ||_||_yrpr)r~rfr)s rbrzModelPrivateAttr.__init__s .rac|dvr,t|j|rt|j|Stt |j d|)zThis function improves compatibility with custom descriptors by ensuring delegation happens as expected when the default value of a private attribute is a descriptor. >__get____set__ __delete__z object has no attribute )hasattrrfr|AttributeErrorrr[)r~items rb __getattr__zModelPrivateAttr.__getattr__sP;;4<<."4<<66 DJ$7$7#::STXS[!\] ]racr|j}|turyt|dd}t|r |||yy)zMPreserve `__set_name__` protocol defined in https://peps.python.org/pep-0487.N __set_name__)rfr r|callable)r~clsnamerfset_names rbrzModelPrivateAttr.__set_name__s<,, ' ' 7ND9 H  S$  racx|jtj|jS|jS)aURetrieve the default value of the object. If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object. If `self.default_factory` is not `None`, it will call `self.default_factory` and return the value returned. Returns: The default value of the object. rrs rbrzModelPrivateAttr.get_defaults37;6J6J6Rv$$T\\2nX\XlXlXnnract||jxr1|j|jf|j|jfk(Srp)r __class__rfr))r~others rb__eq__zModelPrivateAttr.__eq__sF%0 dllDDXDX5Y MM  ! !^ 6  ra)rfrr)r(rr)r rrr)rrrrrrr)rrrrS) r[r\r]r^rr rr TYPE_CHECKINGr rrrr`rarbrrsY -I//fj//Dc/ /    ^  o rar)r)rUcF|tur | tdt||S)aUsage docs: https://docs.pydantic.dev/2.9/concepts/models/#private-model-attributes Indicates that an attribute is intended for private use and not handled during normal validation/serialization. Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner. Private attributes are stored in `__private_attributes__` on the model. Args: default: The attribute's default value. Defaults to Undefined. default_factory: Callable that will be called when a default value is needed for this attribute. If both `default` and `default_factory` are set, an error will be raised. init: Whether the attribute should be included in the constructor of the dataclass. Always `False`. Returns: An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class. Raises: ValueError: If both `default` and `default_factory` are set. rnr)r rzr)rfr)rUs rbrrs16''O,GIJJ ' raceZdZUdZdZded<ded<ded<d ed <d ed <d ed <ded<d ed<ded<ded<ded<ded<eddZy)ComputedFieldInfoa4A container for data from `@computed_field` so that we can access it while building the pydantic-core schema. Attributes: decorator_repr: A class variable representing the decorator string, '@computed_field'. wrapped_property: The wrapped computed field property. return_type: The type of the computed field property's return value. alias: The alias of the property to be used during serialization. alias_priority: The priority of the alias. This affects whether an alias generator is used. title: Title of the computed field to include in the serialization JSON schema. field_title_generator: A callable that takes a field name and returns title for it. description: Description of the computed field to include in the serialization JSON schema. deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. examples: Example values of the computed field to include in the serialization JSON schema. json_schema_extra: A dict or callable to provide extra JSON schema properties. repr: A boolean indicating whether to include the field in the __repr__ output. z@computed_fieldz ClassVar[str]decorator_reprrwrapped_propertyr return_typer*r+r,r-r15typing.Callable[[str, ComputedFieldInfo], str] | Noner3r4rNrr5r6rOrPrSrTc|jyt|jtr|jrdSdSt|jtr |jS|jjSrrrs rbrz%ComputedFieldInfo.deprecation_messagerraNr)r[r\r]r^rr_rrr`rarbrrsh$%6NM5  PP..JJ J ``rarcd}t|trt|jdd}n't|trt|j dd}|j dxr|j d S)z>Returns true if provided property is private, False otherwise.r[___)rrr|fgetrfunc startswith) property_ wrapped_names rb_wrapped_property_is_privater+ scL)X&y~~z2> I /y~~z2>  " "3 ' M 0G0G0M,MMra PropertyT r+r-r1r3r4rr6rPrTrc yrpr`r-s rbrrs/2racyrpr`)__funcs rbrr,s47rac L d f d } || S| |S)aUsage docs: https://docs.pydantic.dev/2.9/concepts/fields#the-computed_field-decorator Decorator to include `property` and `cached_property` when serializing models or dataclasses. This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached. ```py from pydantic import BaseModel, computed_field class Rectangle(BaseModel): width: int length: int @computed_field @property def area(self) -> int: return self.width * self.length print(Rectangle(width=3, length=2).model_dump()) #> {'width': 3, 'length': 2, 'area': 6} ``` If applied to functions not yet decorated with `@property` or `@cached_property`, the function is automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE, and confuse static type checkers, thus explicit use of `@property` is recommended. !!! warning "Mypy Warning" Even with the `@property` or `@cached_property` applied to your function before `@computed_field`, mypy may throw a `Decorated property not supported` error. See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information. To avoid this error message, add `# type: ignore[misc]` to the `@computed_field` line. [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error. ```py import random from pydantic import BaseModel, computed_field class Square(BaseModel): width: float @computed_field def area(self) -> float: # converted to a `property` by `computed_field` return round(self.width**2, 2) @area.setter def area(self, new_area: float) -> None: self.width = new_area**0.5 @computed_field(alias='the magic number', repr=False) def random_number(self) -> int: return random.randint(0, 1_000) square = Square(width=1.3) # `random_number` does not appear in representation print(repr(square)) #> Square(width=1.3, area=1.69) print(square.random_number) #> 3 square.area = 4 print(square.model_dump_json(by_alias=True)) #> {"width":2.0,"area":4.0,"the magic number":3} ``` !!! warning "Overriding with `computed_field`" You can't override a field from a parent class with a `computed_field` in the child class. `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either. See the example below: ```py from pydantic import BaseModel, computed_field class Parent(BaseModel): a: str try: class Child(Parent): @computed_field @property def a(self) -> str: return 'new a' except ValueError as e: print(repr(e)) #> ValueError("you can't override a field with a computed field") ``` Private properties decorated with `@computed_field` have `repr=False` by default. ```py from functools import cached_property from pydantic import BaseModel, computed_field class Model(BaseModel): foo: int @computed_field @cached_property def _private_cached_property(self) -> int: return -self.foo @computed_field @property def _private_property(self) -> int: return -self.foo m = Model(foo=1) print(repr(m)) #> M(foo=1) ``` Args: func: the function to wrap. alias: alias to use when serializing this computed field, only used when `by_alias=True` alias_priority: priority of the alias. This affects whether an alias generator is used title: Title to use when including this computed field in JSON Schema field_title_generator: A callable that takes a field name and returns title for it. description: Description to use when including this computed field in JSON Schema, defaults to the function's docstring deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport). to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the `deprecated` decorator. examples: Example values to use when including this computed field in JSON Schema json_schema_extra: A dict or callable to provide extra JSON schema properties. repr: whether to include this computed field in model repr. Default is `False` for private properties and `True` for public properties. return_type: optional return for serialization logic to expect when serializing to JSON, if included this must be correct, otherwise a `TypeError` is raised. If you don't include a return type Any is used, which does runtime introspection to handle arbitrary objects. Returns: A proxy wrapper for the property. c t tj|}+|jrtj|jt |dr |j tj|}xsdnd t| }n }t|   | }tj||S)N__deprecated__rs)r)) runwrap_wrapped_functionr^inspectcleandocr r3ensure_propertyr+rPydanticDescriptorProxy)f unwrappedrepr_dec_infor+r-rr4r6r3rPrTrr1s rbdeczcomputed_field..decs77:  9#4#4!**9+<+<=K  ')5E"F"11J  ' ' *272C.-A <:QGGEE$     !       221h??ra)r9rrrr`) r'r+r-r1r3r4rr6rPrTrr=s `````````` rbrr0s(z @ @D | 4yra)Jrfrr)r(r+r*r-r,r/r.r0r*r1r*r3r2r4r*r6r5r8r7rMrLrrNrPrOrQr7rRr7rTrSrUr7rVr7rWr7rGrFrCr7rXr7r:r9r<r;r>r=r@r?rBrArHr7rIr,rJr,rDr,rEr,rKz!Literal['smart', 'left_to_right']rYr7rzUnpack[_EmptyKwargs]rr)rfrr)r(rUzLiteral[False]rrr`)r)zcached_property | propertyrrS)r+r*r-r,r1r*r3r r4r*rrNr6r5rPrOrTrSrrrz'typing.Callable[[PropertyT], PropertyT])r0r,rr,rp)r'zPropertyT | Noner+r*r-r,r1r*r3r r4r*rrNr6r5rPrOrTr7rrrz3PropertyT | typing.Callable[[PropertyT], PropertyT])Jr^ __future__r _annotationsrr5sysrrrDataclassField functoolsrrrwarningsr rr pydantic_corer r r r rr#r _internalrrrrrrraliasesrrconfigrerrorsrrr_internal._reprrr__all__r r_ version_infor# TypedDictr%reRepresentationrhrruset signature parametersrremoverr dataclass slots_truerr+TypeVarr,overloadrr`rarbrVsM 2 /% +DDiii,%/ )3 2 w$//*!'>D&,V\$!'!6<17MS $*"!06 )/,2,2,2,2 &!'#!'##4:#IK K5K  K  K < K$K KTKKKK4K/KKK !K""#K$ %K& 'K()K*+K,.-K. /K0'1K2 *3K4 *5K6 *7K8 *9K:;K<=K>?K@AKBCKDEKF2GKHIKJ"KKL MK\(w((/::; : u++: |%!8< ! !5!  !  !H8,778'`'`9'`T N FNN; ' !%SW"15!%MQ( 2  2 2  2 Q 2  2/ 2 2K 2  2 2- 2 277"B!%SW"15!%MQ(B B  B  B  BQBB/BBKB BB9Bra