Xj{JUdZddlmZddlZddlZddlZddlmZddl m Z m Z m Z m Z mZmZmZmZmZddlmZmZddlmZmZdd lmZmZmZdd lmZdd lm Z dd l!m"Z"dd lm#Z#m$Z$ejJdkrddlm&Z&nddl m&Z&ejNZ(ejRdOddiejTGddZ+ejRdOddiejTGddZ,ejRdOddiejTGddZ-ejRdOddiejTGddZ.e rGdde&Z/Gdde&Z0Gdde&Z1Gd d!e&Z2ee0ejfe/ejhfZ5ee2ejle1ejnfZ8ee9e e e fe:e e fee fZ;d"eed'Z?d"ee&ZHGd?d@e&ZIGdAdBe&ZJe eAgeAfZK e eAeje geAfZM eeFeAeEeAfZNeeIeJeGeHfZOeeMeAeKeAfZPe dTdCZQe dUdDZQe dVdEZQ dWdFZQedGZRe re eRd)fZSn)ejRdOiejTGdHdIZSe re eRd)fZTn)ejRdOiejTGdJdKZTedLZUGdMdNZVy)XzBThis module contains related classes and functions for validation.) annotationsN) partialmethod) 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 r/mnt/ssd/data/Dropbox/adrian/vault-secondbrain/venv/lib/python3.12/site-packages/pydantic/functional_validators.py__get_pydantic_core_schema__z+AfterValidator.__get_pydantic_core_schema__Jss%%diigGL  ==tyyIDAA$vV V ;;TYYGD??VT Tc(||jS)Nr"r8cls decorators r4_from_decoratorzAfterValidator._from_decoratorTs ''r6Nr1rr2rreturncore_schema.CoreSchemar;z>_decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]r>r)__name__ __module__ __qualname____doc____annotations__r5 classmethodr<r6r4r r s+(T VUU((r6r 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  r6Nr=r@ rArBrCrDrErrJr5rFr<rGr6r4rIrIYs5@ VU"3C3,  r6rIcDeZdZUdZded<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, got {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"rrJc ddlm} ||}|jdtjd||j |}|j |j }t|jdd}|rz=PlainValidator.__get_pydantic_core_schema__.. !A$r6)functionr* return_schemaplainr%r&)r^rN)pydanticr]getr#wrap_serializer_function_ser_schemarOrJr+r"r r,"with_info_plain_validator_functionr. no_info_plain_validator_function) r0r1r2r]r*r^rSr3r"s r4r5z+PlainValidator.__get_pydantic_core_schema__s ; ![)F#JJ??.!")"9"9+"FM..t/J/JK %diigGL  ==tyyIDAA+)5   ;;TYYGD??+)5 - ! M !sAC55C?>C?cR||j|jjSrUrVr9s r4r<zPlainValidator._from_decoratorrXr6Nr=r@) rArBrCrDrErrJr5rFr<rGr6r4r[r[s6,\ VU"%C%'R  r6r[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"rrJc||}|jturdn|j|j}t|jdd}|r>)5 r6cR||j|jjSrUrVr9s r4r<zWrapValidator._from_decoratorCrXr6Nr=r@rYrGr6r4rprps5$L ^]"3C30  r6rpceZdZddZy)_OnlyValueValidatorClsMethodcyr`rGr0r:values r4__call__z%_OnlyValueValidatorClsMethod.__call__Nr6Nr:rr|rr>rrArBrCr}rGr6r4ryryMs?r6ryceZdZddZy)_V2ValidatorClsMethodcyr`rGr0r:r|rWs r4r}z_V2ValidatorClsMethod.__call__Qr~r6Nr:rr|rrWcore_schema.ValidationInfo[Any]r>rrrGr6r4rrPsfr6rceZdZddZy) _OnlyValueWrapValidatorClsMethodcyr`rGr0r:r|r2s r4r}z)_OnlyValueWrapValidatorClsMethod.__call__Tr~r6N)r:rr|rr2(core_schema.ValidatorFunctionWrapHandlerr>rrrGr6r4rrSsrr6rc(eZdZ ddZy)_V2WrapValidatorClsMethodcyr`rGr0r:r|r2rWs r4r}z"_V2WrapValidatorClsMethod.__call__Wsr6N) r:rr|rr2rrWrr>rrrGr6r4rrVs7   >   2   r6rr_PartialClsOrStaticMethod"_V2BeforeAfterOrPlainValidatorType)bound_V2WrapValidatorType)rLr$rrrhFieldValidatorModes.) check_fieldsrJcyr`rGr%r'rrJfieldss r4field_validatorrys>Ar6cyr`rGrs r4rrs Z]r6)r'rcyr`rG)r%r'rrs r4rrs Z]r6r$)r'rrJc t|st|tr tdddvrturtddtur dk(rt |gt dDs td d  d fd }|S) a!!! 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: *fields: The field names the validator should apply to. 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'`. 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. - If `json_schema_input_type` is provided with an unsupported `mode`. - If the decorator is applied to an instance method. zThe `@field_validator` decorator cannot be used without arguments, at least one field must be provided. For example: `@field_validator('', ...)`.zdecorator-missing-argumentscode)rLrhrrz;`json_schema_input_type` can't be used when mode is set to zvalidator-input-typerhc3<K|]}t|tywr`) isinstancestr).0r%s r4 z"field_validator..s:%z%%:szThe provided field names to the `@field_validator` decorator should be strings. For example: `@field_validator('', '', ...).`zdecorator-invalid-fieldsctj|r tddtj|}tj}tj ||S)NzFThe `@field_validator` decorator cannot be applied to instance methodszvalidator-instance-methodr)rr'rrJ)ris_instance_method_from_sigr%ensure_classmethod_based_on_signatureFieldValidatorDecoratorInfoPydanticDescriptorProxy)fdec_inforrrJr's r4deczfield_validator..decsg  2 21 5#X0   = =a @::(_decorators.PydanticDescriptorProxy[Any])callablerrFrrrall)r%r'rrJrrs ```` r4rrs@*UK8 D.   ..3IQb3bI$ R'  !22tw!$ ^V^F :6: : X+  @ S@ 1@@" Jr6 _ModelType _ModelTypeCo) covariantc&eZdZdZ d ddZy)ModelWrapValidatorHandlerz]`@model_validator` decorated function handler argument type. This is used when `mode='wrap'`.Ncyr`rG)r0r|outer_locations r4r}z"ModelWrapValidatorHandler.__call__ s r6r`)r|rrzstr | int | Noner>rrArBrCrDr}rGr6r4rr s+g ,0  )   r6rc(eZdZdZ ddZy)ModelWrapValidatorWithoutInfozA `@model_validator` decorated function signature. This is used when `mode='wrap'` and the function does not have info argument. cyr`rGrs r4r}z&ModelWrapValidatorWithoutInfo.__call__sr6N)r:type[_ModelType]r|rr2%ModelWrapValidatorHandler[_ModelType]r>rrrGr6r4rrs2     7   r6rc,eZdZdZ ddZy)ModelWrapValidatorzSA `@model_validator` decorated function signature. This is used when `mode='wrap'`.cyr`rGrs r4r}zModelWrapValidator.__call__)sr6N) r:rr|rr2rrWzcore_schema.ValidationInfor>rrrGr6r4rr&s:]     7 )   r6rc eZdZdZ ddZy)#FreeModelBeforeValidatorWithoutInfoA `@model_validator` decorated function signature. This is used when `mode='before'` and the function does not have info argument. cyr`rG)r0r|s r4r}z,FreeModelBeforeValidatorWithoutInfo.__call__;sr6N)r|rr>rrrGr6r4rr6s    r6rc$eZdZdZ ddZy)ModelBeforeValidatorWithoutInforcyr`rGr{s r4r}z(ModelBeforeValidatorWithoutInfo.__call__Jr6NrrrGr6r4rrEs(    r6rc$eZdZdZ ddZy)FreeModelBeforeValidatorUA `@model_validator` decorated function signature. This is used when `mode='before'`.cyr`rG)r0r|rWs r4r}z!FreeModelBeforeValidator.__call__Xrr6N)r|rrWrr>rrrGr6r4rrUs(_   .  r6rc(eZdZdZ ddZy)ModelBeforeValidatorrcyr`rGrs r4r}zModelBeforeValidator.__call__fsr6NrrrGr6r4rrcs0_     .   r6rcyr`rGr's r4model_validatorr r6cyr`rGrs r4rrrr6cyr`rGrs r4rrrr6cdfd }|S)a@!!! abstract "Usage Documentation" [Model Validators](../concepts/validators.md#model-validators) Decorate model methods for validation purposes. Example usage: ```python from typing_extensions import Self from pydantic import BaseModel, ValidationError, model_validator class Square(BaseModel): width: float height: float @model_validator(mode='after') def verify_square(self) -> 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) rrrrFwarningswarnrrModelValidatorDecoratorInfor)rrr's r4rzmodel_validator..decsw  = =a @ 7?z![9 MM3JJW/IZ[GH  ::E221h??r6)rrr>rrG)r'rs` r4rrsb@ Jr6AnyTypecLeZdZdZeddZeddZejZy) 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||fSr`)rr:items r4__class_getitem__zInstanceOf.__class_getitem__ sT35[) )r6cddlm}tjt j |xs|} ||}tj d||d<tj||S#|$r|cYSwxYw)Nr)GENERATE_SCHEMA_ERRORSc||Sr`rGras r4rdz9InstanceOf.__get_pydantic_core_schema__..rer6rfr*r^) python_schema json_schema)#pydantic._internal._generate_schemarris_instance_schemar get_originrkjson_or_python_schema)r:sourcer2rinstance_of_schemaoriginal_schemas r4r5z'InstanceOf.__get_pydantic_core_schema__s R"-!?!? @T@TU[@\@f`f!g  x")&/ 7B6e6e.7"?3#88GYgvww* *)) *sA..A87A8N)rrr>rrrr2rr>r?) rArBrCrDrFrr5object__hash__rGr6r4rrs= @  *  *  x  x&??r6rcBeZdZdZddZeddZejZy)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|tfSr`)rrrs r4rz SkipValidation.__class_getitem__7sT>#334 4r6ctj5tjdt||ddddfdgi}t j |t j dS#1swY>xYw)Nignore pydantic_js_annotation_functionsc|Sr`rG)_crcrs r4rdz=SkipValidation.__get_pydantic_core_schema__..?s 1_K]r6c||Sr`rGras r4rdz=SkipValidation.__get_pydantic_core_schema__..Crer6r)metadatar^)rcatch_warnings simplefilterrr any_schemark)r:rr2rrs @r4r5z+SkipValidation.__get_pydantic_core_schema__:sw((* 2%%h0DE")&/ 2;=]<^_H))!)MM.   2 2s #A66A?N)rrr>rr) rArBrCrDrrFr5rrrGr6r4rr*s+  5    ??r6r _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 ||_||_yr`) from_typeinstantiation_hook)r0rrs r4__init__zValidateAs.__init__ps""4r6ch||j}tj|j|S)Nr))rrr/r)r0rr2r*s r4r5z'ValidateAs.__get_pydantic_core_schema__ts/(;;  # #  r6N)rzCallable[[_FromTypeT], Any]rztype[_FromTypeT]r>Noner)rArBrCrDrr5rGr6r4rrMsD5 r6rrG) r%rrrr'Literal['wrap']r bool | NonerJrr>z6Callable[[_V2WrapValidatorType], _V2WrapValidatorType]) r%rrrr'zLiteral['before', 'plain']rr rJrr>RCallable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]) r%rrrr'Literal['after']rr r>r ) r%rrrr'rrr rJrr>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)WrD __future__r _annotations dataclassessysr functoolsrtypingrrrrr r r r r pydantic_corerrtyping_extensionsrr _internalrrrannotated_handlersrerrorsrversionrrr version_inforinspect_validatorr+ dataclass slots_truer rIr[rpryrrrr,r. _V2Validatorrsru_V2WrapValidatorrF staticmethodrrErrrrrrValidatorFunctionWrapHandlerrrrrrrrModelAfterValidatorWithoutInfoValidationInfoModelAfterValidator_AnyModelWrapValidator_AnyModelBeforeValidator_AnyModelAfterValidatorrrrrrrrGr6r4r(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 i ii  i  i  iiX\ " ~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;;<##=#>\ " , , r6