fL i_|VUdZddlmZddlZddlZddlZddlmZddl m Z ddl m Z m Z mZmZmZmZmZmZmZddlmZmZddlmZmZd d lmZmZmZd d lm Z d d l!m"Z"d d l#m$Z$d dlm%Z%m&Z&ejNdkrddlm(Z(nddl m(Z(ejRZ*ejVdPddiejXGddZ-ejVdPddiejXGddZ.ejVdPddiejXGddZ/ejVdPddiejXGddZ0e rGdde(Z1Gdde(Z2Gdd e(Z3Gd!d"e(Z4ee2ejje1ejlfZ7ee4ejpe3ejrfZ:ee;eeefed$<ed%ee7e=f&Z?ed'ee:e=f&Z@ed(ZAd#e>d)<ed*d*d+ dQd,ZBed*d*d+ dRd-ZBed*d*d. dSd/ZBd0ded1 dTd2ZBed3ZCed4d5ZDGd6d7eje(eDZFGd8d9e(eCZGGd:d;e(eCZHGd<d=e(ZIGd>d?e(ZJGd@dAe(ZKGdBdCe(ZLeeCgeCfZM eeCejegeCfZO eeHeCeGeCfZPeeKeLeIeJfZQeeOeCeMeCfZRe dUdDZSe dVdEZSe dWdFZS dXdGZSedHZTe re eTd*fZUn)ejVdPiejXGdIdJZUe re eTd*fZVn)ejVdPiejXGdKdLZVedMZWGdNdOZXy)YzBThis module contains related classes and functions for validation.) annotationsN) partialmethod) FunctionType) TYPE_CHECKING AnnotatedAnyCallableLiteralTypeVarUnioncastoverload)PydanticUndefined core_schema)Self TypeAlias) _decorators _generics_internal_dataclass)GetCoreSchemaHandler)PydanticUserError) version_short)ArbitraryTypeWarningPydanticDeprecatedSince212) )ProtocolfrozenTc6eZdZUdZded<ddZeddZy) AfterValidatoraT!!! abstract "Usage Documentation" [field *after* validators](../concepts/validators.md#field-after-validator) A metadata class that indicates that a validation should be applied **after** the inner validation logic. Attributes: func: The validator function. Example: ```python from typing import Annotated from pydantic import AfterValidator, BaseModel, ValidationError MyInt = Annotated[int, AfterValidator(lambda v: v + 1)] class Model(BaseModel): a: MyInt print(Model(a=1).a) #> 2 try: Model(a='a') except ValidationError as e: print(e.json(indent=2)) ''' [ { "type": "int_parsing", "loc": [ "a" ], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "a", "url": "https://errors.pydantic.dev/2/v/int_parsing" } ] ''' ``` Kcore_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunctionfuncc2||}t|jdd}|r;ttj|j}tj ||Sttj |j}tj||S)Nafterfieldmodetypeschema)_inspect_validatorr#r rWithInfoValidatorFunction"with_info_after_validator_functionNoInfoValidatorFunction no_info_after_validator_function)self source_typehandlerr+info_argr#s d/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/pydantic/functional_validators.py__get_pydantic_core_schema__z+AfterValidator.__get_pydantic_core_schema__Kss%%diigGL  ==tyyIDAA$vV V ;;TYYGD??VT Tc(||jS)Nr#r9cls decorators r5_from_decoratorzAfterValidator._from_decoratorUs ''r7Nr2rr3rreturncore_schema.CoreSchemar<z>_decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]r?r)__name__ __module__ __qualname____doc____annotations__r6 classmethodr=r7r5r!r!s+(T VUU((r7r!cDeZdZUdZded<eZded<d dZed dZ y) BeforeValidatora!!! abstract "Usage Documentation" [field *before* validators](../concepts/validators.md#field-before-validator) A metadata class that indicates that a validation should be applied **before** the inner validation logic. Attributes: func: The validator function. json_schema_input_type: The input type used to generate the appropriate JSON Schema (in validation mode). The actual input type is `Any`. Example: ```python from typing import Annotated from pydantic import BaseModel, BeforeValidator MyInt = Annotated[int, BeforeValidator(lambda v: v + 1)] class Model(BaseModel): a: MyInt print(Model(a=1).a) #> 2 try: Model(a='a') except TypeError as e: print(e) #> can only concatenate str (not "int") to str ``` r"r#rjson_schema_input_typec||}|jturdn|j|j}t|jdd}|r>#H#H  r7Nr>rA rBrCrDrErFrrKr6rGr=rHr7r5rJrJZs5@ VU"3C3,  r7rJcDeZdZUdZded<eZded<d dZed dZ y) PlainValidatora!!! abstract "Usage Documentation" [field *plain* validators](../concepts/validators.md#field-plain-validator) A metadata class that indicates that a validation should be applied **instead** of the inner validation logic. !!! note Before v2.9, `PlainValidator` wasn't always compatible with JSON Schema generation for `mode='validation'`. You can now use the `json_schema_input_type` argument to specify the input type of the function to be used in the JSON schema when `mode='validation'` (the default). See the example below for more details. Attributes: func: The validator function. json_schema_input_type: The input type used to generate the appropriate JSON Schema (in validation mode). The actual input type is `Any`. Example: ```python from typing import Annotated, Union from pydantic import BaseModel, PlainValidator def validate(v: object) -> int: if not isinstance(v, (int, str)): raise ValueError(f'Expected int or str, go {type(v)}') return int(v) + 1 MyInt = Annotated[ int, PlainValidator(validate, json_schema_input_type=Union[str, int]), # (1)! ] class Model(BaseModel): a: MyInt print(Model(a='1').a) #> 2 print(Model(a=1).a) #> 2 ``` 1. In this example, we've specified the `json_schema_input_type` as `Union[str, int]` which indicates to the JSON schema generator that in validation mode, the input type for the `a` field can be either a [`str`][] or an [`int`][]. r"r#rrKc ddlm} ||}|jdtjd||j |}|j |j }t|jdd}|rz=PlainValidator.__get_pydantic_core_schema__.. !A$r7)functionr+ return_schemaplainr&r')r`rO)pydanticr_getr#wrap_serializer_function_ser_schemarPrKr,r#r r-"with_info_plain_validator_functionr/ no_info_plain_validator_function) r1r2r3r_r+r`rTr4r#s r5r6z+PlainValidator.__get_pydantic_core_schema__s ; ![)F#JJ??.!")"9"9+"FM..t/J/JK %diigGL  ==tyyIDAA+)5   ;;TYYGD??+)5 - ! M !sAC55C?>C?cR||j|jjSrVrWr:s r5r=zPlainValidator._from_decoratorrYr7Nr>rA) rBrCrDrErFrrKr6rGr=rHr7r5r\r\s6,\ VU"%C%'R  r7r\cDeZdZUdZded<eZded<d dZed dZ y) WrapValidatora!!! abstract "Usage Documentation" [field *wrap* validators](../concepts/validators.md#field-wrap-validator) A metadata class that indicates that a validation should be applied **around** the inner validation logic. Attributes: func: The validator function. json_schema_input_type: The input type used to generate the appropriate JSON Schema (in validation mode). The actual input type is `Any`. ```python from datetime import datetime from typing import Annotated from pydantic import BaseModel, ValidationError, WrapValidator def validate_timestamp(v, handler): if v == 'now': # we don't want to bother with further validation, just return the new value return datetime.now() try: return handler(v) except ValidationError: # validation failed, in this case we want to return a default value return datetime(2000, 1, 1) MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)] class Model(BaseModel): a: MyTimestamp print(Model(a='now').a) #> 2032-01-02 03:04:05.000006 print(Model(a='invalid').a) #> 2000-01-01 00:00:00 ``` zScore_schema.NoInfoWrapValidatorFunction | core_schema.WithInfoWrapValidatorFunctionr#rrKc||}|jturdn|j|j}t|jdd}|r>)5 r7cR||j|jjSrVrWr:s r5r=zWrapValidator._from_decoratorDrYr7Nr>rArZrHr7r5rrrrs5$L ^]"3C30  r7rrceZdZddZy)_OnlyValueValidatorClsMethodcyrbrHr1r;values r5__call__z%_OnlyValueValidatorClsMethod.__call__Or7Nr;rr~rr?rrBrCrDrrHr7r5r{r{Ns?r7r{ceZdZddZy)_V2ValidatorClsMethodcyrbrHr1r;r~rXs r5rz_V2ValidatorClsMethod.__call__Rrr7Nr;rr~rrXcore_schema.ValidationInfo[Any]r?rrrHr7r5rrQsfr7rceZdZddZy) _OnlyValueWrapValidatorClsMethodcyrbrHr1r;r~r3s r5rz)_OnlyValueWrapValidatorClsMethod.__call__Urr7N)r;rr~rr3(core_schema.ValidatorFunctionWrapHandlerr?rrrHr7r5rrTsrr7rc(eZdZ ddZy)_V2WrapValidatorClsMethodcyrbrHr1r;r~r3rXs r5rz"_V2WrapValidatorClsMethod.__call__Xsr7N) r;rr~rr3rrXrr?rrrHr7r5rrWs7   >   2   r7rr_PartialClsOrStaticMethod"_V2BeforeAfterOrPlainValidatorType)bound_V2WrapValidatorType)rMr%rtrjFieldValidatorModes.) check_fieldsrKcyrbrHr&r(rrKfieldss r5field_validatorrzs>Ar7cyrbrHrs r5rrs Z]r7)r(rcyrbrH)r&r(rrs r5rrs Z]r7r%)r(rrKc t|tr tdddvrturtddtur dk(rt|gt dDs td d  d fd }|S) aO!!! abstract "Usage Documentation" [field validators](../concepts/validators.md#field-validators) Decorate methods on the class indicating that they should be used to validate fields. Example usage: ```python from typing import Any from pydantic import ( BaseModel, ValidationError, field_validator, ) class Model(BaseModel): a: str @field_validator('a') @classmethod def ensure_foobar(cls, v: Any): if 'foobar' not in v: raise ValueError('"foobar" not found in a') return v print(repr(Model(a='this is foobar good'))) #> Model(a='this is foobar good') try: Model(a='snap') except ValidationError as exc_info: print(exc_info) ''' 1 validation error for Model a Value error, "foobar" not found in a [type=value_error, input_value='snap', input_type=str] ''' ``` For more in depth examples, see [Field Validators](../concepts/validators.md#field-validators). Args: field: The first field the `field_validator` should be called on; this is separate from `fields` to ensure an error is raised if you don't pass at least one. *fields: Additional field(s) the `field_validator` should be called on. mode: Specifies whether to validate the fields before or after validation. check_fields: Whether to check that the fields actually exist on the model. json_schema_input_type: The input type of the function. This is only used to generate the appropriate JSON Schema (in validation mode) and can only specified when `mode` is either `'before'`, `'plain'` or `'wrap'`. Returns: A decorator that can be used to decorate a function to be used as a field_validator. Raises: PydanticUserError: - If `@field_validator` is used bare (with no fields). - If the args passed to `@field_validator` as fields are not strings. - If `@field_validator` applied to instance methods. z`@field_validator` should be used with fields and keyword arguments, not bare. E.g. usage should be `@validator('', ...)`zvalidator-no-fieldscode)rMrjrtz;`json_schema_input_type` can't be used when mode is set to zvalidator-input-typerjc3<K|]}t|tywrb) isinstancestr).0r&s r5 z"field_validator..s:%z%%:sz`@field_validator` fields should be passed as separate string args. E.g. usage should be `@validator('', '', ...)`zvalidator-invalid-fieldsctj|r tddtj|}tj}tj ||S)Nz8`@field_validator` cannot be applied to instance methodszvalidator-instance-methodr)rr(rrK)ris_instance_method_from_sigr%ensure_classmethod_based_on_signatureFieldValidatorDecoratorInfoPydanticDescriptorProxy)fdec_inforrrKr(s r5deczfield_validator..decsg  2 21 5#JQl   = =a @:: Self: if self.width != self.height: raise ValueError('width and height do not match') return self s = Square(width=1, height=1) print(repr(s)) #> Square(width=1.0, height=1.0) try: Square(width=1, height=2) except ValidationError as e: print(e) ''' 1 validation error for Square Value error, width and height do not match [type=value_error, input_value={'width': 1, 'height': 2}, input_type=dict] ''' ``` For more in depth examples, see [Model Validators](../concepts/validators.md#model-validators). Args: mode: A required string literal that specifies the validation mode. It can be one of the following: 'wrap', 'before', or 'after'. Returns: A decorator that can be used to decorate a function to be used as a model validator. ctj|}dk(r8t|tr(t j t dtddtj}tj||S)Nr%zUsing `@model_validator` with mode='after' on a classmethod is deprecated. Instead, use an instance method. See the documentation at https://docs.pydantic.dev/z,/concepts/validators/#model-after-validator.)categorymessage stacklevelr) rrrrGwarningswarnrrModelValidatorDecoratorInfor)rrr(s r5rzmodel_validator..decsw  = =a @ 7?z![9 MM3JJW/IZ[GH  ::E221h??r7)rrr?rrH)r(rs` r5rrsb@ Jr7AnyTypecLeZdZdZeddZeddZejZy) InstanceOfuGeneric type for annotating a type that is an instance of a given class. Example: ```python from pydantic import BaseModel, InstanceOf class Foo: ... class Bar(BaseModel): foo: InstanceOf[Foo] Bar(foo=Foo()) try: Bar(foo=42) except ValidationError as e: print(e) """ [ │ { │ │ 'type': 'is_instance_of', │ │ 'loc': ('foo',), │ │ 'msg': 'Input should be an instance of Foo', │ │ 'input': 42, │ │ 'ctx': {'class': 'Foo'}, │ │ 'url': 'https://errors.pydantic.dev/0.38.0/v/is_instance_of' │ } ] """ ``` c"t||fSrb)rr;items r5__class_getitem__zInstanceOf.__class_getitem__sT35[) )r7cddlm}tjt j |xs|} ||}tj d||d<tj||S#|$r|cYSwxYw)Nrr^c||SrbrHrcs r5rfz9InstanceOf.__get_pydantic_core_schema__..#rgr7rhr+r`) python_schema json_schema)rkr_ris_instance_schemar get_originrmjson_or_python_schema)r;sourcer3r_instance_of_schemaoriginal_schemas r5r6z'InstanceOf.__get_pydantic_core_schema__s >"-!?!? @T@TU[@\@f`f!g  x")&/ 7B6e6e.7"?3#88GYgvww1 *)) *sA..A87A8N)rrr?rrrr3rr?r@) rBrCrDrErGrr6object__hash__rHr7r5rrs= @  *  *  x  x&??r7rcBeZdZdZddZeddZejZy)SkipValidationaIf this is applied as an annotation (e.g., via `x: Annotated[int, SkipValidation]`), validation will be skipped. You can also use `SkipValidation[int]` as a shorthand for `Annotated[int, SkipValidation]`. This can be useful if you want to use a type annotation for documentation/IDE/type-checking purposes, and know that it is safe to skip validation for one or more of the fields. Because this converts the validation schema to `any_schema`, subsequent annotation-applied transformations may not have the expected effects. Therefore, when used, this annotation should generally be the final annotation applied to a type. c(t|tfSrb)rrrs r5rz SkipValidation.__class_getitem__;sT>#334 4r7ctj5tjdt||ddddfdgi}t j |t j dS#1swY>xYw)Nignore pydantic_js_annotation_functionsc|SrbrH)_crers r5rfz=SkipValidation.__get_pydantic_core_schema__..Cs 1_K]r7c||SrbrHrcs r5rfz=SkipValidation.__get_pydantic_core_schema__..Grgr7r)metadatar`)rcatch_warnings simplefilterrr any_schemarm)r;rr3rrs @r5r6z+SkipValidation.__get_pydantic_core_schema__>sw((* 2%%h0DE")&/ 2;=]<^_H))!)MM.   2 2s #A66A?N)rrr?rr) rBrCrDrErrGr6rrrHr7r5rr.s+  5    ??r7r _FromTypeTc eZdZdZddZddZy) ValidateAsaA helper class to validate a custom type from a type that is natively supported by Pydantic. Args: from_type: The type natively supported by Pydantic to use to perform validation. instantiation_hook: A callable taking the validated type as an argument, and returning the populated custom type. Example: ```python {lint="skip"} from typing import Annotated from pydantic import BaseModel, TypeAdapter, ValidateAs class MyCls: def __init__(self, a: int) -> None: self.a = a def __repr__(self) -> str: return f"MyCls(a={self.a})" class Model(BaseModel): a: int ta = TypeAdapter( Annotated[MyCls, ValidateAs(Model, lambda v: MyCls(a=v.a))] ) print(ta.validate_python({'a': 1})) #> MyCls(a=1) ``` c ||_||_yrb) from_typeinstantiation_hook)r1rrs r5__init__zValidateAs.__init__ts""4r7ch||j}tj|j|S)Nr*)rrr0r)r1rr3r+s r5r6z'ValidateAs.__get_pydantic_core_schema__xs/(;;  # #  r7N)rzCallable[[_FromTypeT], Any]rztype[_FromTypeT]r?Noner)rBrCrDrErr6rHr7r5rrQsD5 r7rrH) r&rrrr(Literal['wrap']r bool | NonerKrr?z6Callable[[_V2WrapValidatorType], _V2WrapValidatorType]) r&rrrr(zLiteral['before', 'plain']rr rKrr?RCallable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]) r&rrrr(Literal['after']rr r?r ) r&rrrr(rrr rKrr?zCallable[[Any], Any])r(r r?z|Callable[[_AnyModelWrapValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]])r(zLiteral['before']r?zrCallable[[_AnyModelBeforeValidator], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]])r(r r?z}Callable[[_AnyModelAfterValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]])r(z"Literal['wrap', 'before', 'after']r?r)YrE __future__r _annotations dataclassessysr functoolsrtypesrtypingrrrr r r r r r pydantic_corerrtyping_extensionsrr _internalrrrannotated_handlersrerrorsrversionrrr version_inforinspect_validatorr, dataclass slots_truer!rJr\rrr{rrrr-r/ _V2Validatorrurw_V2WrapValidatorrG staticmethodrrFrrrrrrValidatorFunctionWrapHandlerrrrrrrrModelAfterValidatorWithoutInfoValidationInfoModelAfterValidator_AnyModelWrapValidator_AnyModelBeforeValidator_AnyModelAfterValidatorrrrrrrrHr7r5r(sH2 #ccc8-BB4%"Fg* 22EdE&9&D&DE9(9(F9(xEdE&9&D&DE? ? F? DEdE&9&D&DE` ` F` FEdE&9&D&DEG G FG T@x@ggs8sH--$++ -L!11(// 1,1S#s]1K\Z]_bZbMcersvew1w+xyx)0,L";;<*&##9GWYrGrAst!()K!LYL !$"% A AA  A  A  A<A A !$"% ] ]] % ]  ]  ]X] ] ! # ] ]]  ]  ] X ] ]!( $"3 l ll  l  l  ll^\ " ~6   H H(S_J`  HZ$8" *-  (  h  x  8 "*:, *B!C K,F,Fs,KLjXYZ1*=?\]g?hhi 24WYxx 3J ?A_`jAk kl         A ,A AH ) 7C<(J[<0;;<9#9#=9#xw|,N[<0;;<##=#>\ " , , r7