Coverage for pydantic / functional_validators.py: 100.00%
163 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
1"""This module contains related classes and functions for validation."""
3from __future__ import annotations as _annotations 1gabjklhcdmnosiefpqr
5import dataclasses 1gabjklhcdmnosiefpqr
6import warnings 1gabjklhcdmnosiefpqr
7from collections.abc import Callable 1gabjklhcdmnosiefpqr
8from functools import partialmethod 1gabjklhcdmnosiefpqr
9from typing import TYPE_CHECKING, Annotated, Any, Literal, Protocol, Self, TypeAlias, TypeVar, cast, overload 1gabjklhcdmnosiefpqr
11from pydantic_core import PydanticUndefined, core_schema 1gabjklhcdmnosiefpqr
12from typing_extensions import TypeForm 1gabjklhcdmnosiefpqr
14from ._internal import _decorators, _generics 1gabjklhcdmnosiefpqr
15from .annotated_handlers import GetCoreSchemaHandler 1gabjklhcdmnosiefpqr
16from .errors import PydanticUserError 1gabjklhcdmnosiefpqr
17from .warnings import ArbitraryTypeWarning 1gabjklhcdmnosiefpqr
19_inspect_validator = _decorators.inspect_validator 1gabjklhcdmnosiefpqr
22@dataclasses.dataclass(frozen=True, slots=True) 1gabjklhcdmnosiefpqr
23class AfterValidator: 1gabjklhcdmnosiefpqr
24 """!!! abstract "Usage Documentation"
25 [field *after* validators](../concepts/validators.md#field-after-validator)
27 A metadata class that indicates that a validation should be applied **after** the inner validation logic.
29 Attributes:
30 func: The validator function.
32 Example:
33 ```python
34 from typing import Annotated
36 from pydantic import AfterValidator, BaseModel, ValidationError
38 MyInt = Annotated[int, AfterValidator(lambda v: v + 1)]
40 class Model(BaseModel):
41 a: MyInt
43 print(Model(a=1).a)
44 #> 2
46 try:
47 Model(a='a')
48 except ValidationError as e:
49 print(e.json(indent=2))
50 '''
51 [
52 {
53 "type": "int_parsing",
54 "loc": [
55 "a"
56 ],
57 "msg": "Input should be a valid integer, unable to parse string as an integer",
58 "input": "a",
59 "url": "https://errors.pydantic.dev/2/v/int_parsing"
60 }
61 ]
62 '''
63 ```
64 """
66 func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction 1gabjklhcdmnosiefpqr
68 def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1gabjklhcdmnosiefpqr
69 schema = handler(source_type) 1gabjklhcdmnosiefpqr
70 info_arg = _inspect_validator(self.func, mode='after', type='field') 1gabjklhcdmnosiefpqr
71 if info_arg: 1gabjklhcdmnosiefpqr
72 func = cast(core_schema.WithInfoValidatorFunction, self.func) 1gabjklhcdmnoiefpqr
73 return core_schema.with_info_after_validator_function(func, schema=schema) 1gabjklhcdmnoiefpqr
74 else:
75 func = cast(core_schema.NoInfoValidatorFunction, self.func) 1gabjklhcdmnosiefpqr
76 return core_schema.no_info_after_validator_function(func, schema=schema) 1gabjklhcdmnosiefpqr
78 @classmethod 1gabjklhcdmnosiefpqr
79 def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self: 1gabjklhcdmnosiefpqr
80 return cls(func=decorator.func) 1gabjklhcdmnosiefpqr
83@dataclasses.dataclass(frozen=True, slots=True) 1gabjklhcdmnosiefpqr
84class BeforeValidator: 1gabjklhcdmnosiefpqr
85 """!!! abstract "Usage Documentation"
86 [field *before* validators](../concepts/validators.md#field-before-validator)
88 A metadata class that indicates that a validation should be applied **before** the inner validation logic.
90 Attributes:
91 func: The validator function.
92 json_schema_input_type: The input type used to generate the appropriate
93 JSON Schema (in validation mode). The actual input type is `Any`.
95 Example:
96 ```python
97 from typing import Annotated
99 from pydantic import BaseModel, BeforeValidator
101 MyInt = Annotated[int, BeforeValidator(lambda v: v + 1)]
103 class Model(BaseModel):
104 a: MyInt
106 print(Model(a=1).a)
107 #> 2
109 try:
110 Model(a='a')
111 except TypeError as e:
112 print(e)
113 #> can only concatenate str (not "int") to str
114 ```
115 """
117 func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction 1gabjklhcdmnosiefpqr
118 json_schema_input_type: Any = PydanticUndefined 1gabjklhcdmnosiefpqr
120 def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1gabjklhcdmnosiefpqr
121 schema = handler(source_type) 1gabjklhcdmnoiefpqr
122 input_schema = ( 1gabjklhcdmnoiefpqr
123 None
124 if self.json_schema_input_type is PydanticUndefined
125 else handler.generate_schema(self.json_schema_input_type)
126 )
128 info_arg = _inspect_validator(self.func, mode='before', type='field') 1gabjklhcdmnoiefpqr
129 if info_arg: 1gabjklhcdmnoiefpqr
130 func = cast(core_schema.WithInfoValidatorFunction, self.func) 1gabjklhcdmnoiefpqr
131 return core_schema.with_info_before_validator_function( 1gabjklhcdmnoiefpqr
132 func,
133 schema=schema,
134 json_schema_input_schema=input_schema,
135 )
136 else:
137 func = cast(core_schema.NoInfoValidatorFunction, self.func) 1gabjklhcdmnoiefpqr
138 return core_schema.no_info_before_validator_function( 1gabjklhcdmnoiefpqr
139 func, schema=schema, json_schema_input_schema=input_schema
140 )
142 @classmethod 1gabjklhcdmnosiefpqr
143 def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self: 1gabjklhcdmnosiefpqr
144 return cls( 1gabjklhcdmnoiefpqr
145 func=decorator.func,
146 json_schema_input_type=decorator.info.json_schema_input_type,
147 )
150@dataclasses.dataclass(frozen=True, slots=True) 1gabjklhcdmnosiefpqr
151class PlainValidator: 1gabjklhcdmnosiefpqr
152 """!!! abstract "Usage Documentation"
153 [field *plain* validators](../concepts/validators.md#field-plain-validator)
155 A metadata class that indicates that a validation should be applied **instead** of the inner validation logic.
157 !!! note
158 Before v2.9, `PlainValidator` wasn't always compatible with JSON Schema generation for `mode='validation'`.
159 You can now use the `json_schema_input_type` argument to specify the input type of the function
160 to be used in the JSON schema when `mode='validation'` (the default). See the example below for more details.
162 Attributes:
163 func: The validator function.
164 json_schema_input_type: The input type used to generate the appropriate
165 JSON Schema (in validation mode). The actual input type is `Any`.
167 Example:
168 ```python
169 from typing import Annotated
171 from pydantic import BaseModel, PlainValidator
173 def validate(v: object) -> int:
174 if not isinstance(v, (int, str)):
175 raise ValueError(f'Expected int or str, got {type(v)}')
177 return int(v) + 1
179 MyInt = Annotated[
180 int,
181 PlainValidator(validate, json_schema_input_type=str | int), # (1)!
182 ]
184 class Model(BaseModel):
185 a: MyInt
187 print(Model(a='1').a)
188 #> 2
190 print(Model(a=1).a)
191 #> 2
192 ```
194 1. In this example, we've specified the `json_schema_input_type` as `Union[str, int]` which indicates to the JSON schema
195 generator that in validation mode, the input type for the `a` field can be either a [`str`][] or an [`int`][].
196 """
198 func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction 1gabjklhcdmnosiefpqr
199 json_schema_input_type: Any = Any 1gabjklhcdmnosiefpqr
201 def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1gabjklhcdmnosiefpqr
202 # Note that for some valid uses of PlainValidator, it is not possible to generate a core schema for the
203 # source_type, so calling `handler(source_type)` will error, which prevents us from generating a proper
204 # serialization schema. To work around this for use cases that will not involve serialization, we simply
205 # catch any PydanticSchemaGenerationError that may be raised while attempting to build the serialization schema
206 # and abort any attempts to handle special serialization.
207 from pydantic import PydanticSchemaGenerationError 1gabjklhcdmnoiefpqr
209 try: 1gabjklhcdmnoiefpqr
210 schema = handler(source_type) 1gabjklhcdmnoiefpqr
211 # TODO if `schema['serialization']` is one of `'include-exclude-dict/sequence',
212 # schema validation will fail. That's why we use 'type ignore' comments below.
213 serialization = schema.get( 1gabjklhcdmnoiefpqr
214 'serialization',
215 core_schema.wrap_serializer_function_ser_schema(
216 function=lambda v, h: h(v),
217 schema=schema,
218 return_schema=handler.generate_schema(source_type),
219 ),
220 )
221 except PydanticSchemaGenerationError: 1gabjklhcdmnoiefpqr
222 serialization = None 1gabjklhcdmnoiefpqr
224 input_schema = handler.generate_schema(self.json_schema_input_type) 1gabjklhcdmnoiefpqr
226 info_arg = _inspect_validator(self.func, mode='plain', type='field') 1gabjklhcdmnoiefpqr
227 if info_arg: 1gabjklhcdmnoiefpqr
228 func = cast(core_schema.WithInfoValidatorFunction, self.func) 1gabjklhcdmnoiefpqr
229 return core_schema.with_info_plain_validator_function( 1gabjklhcdmnoiefpqr
230 func,
231 serialization=serialization, # pyright: ignore[reportArgumentType]
232 json_schema_input_schema=input_schema,
233 )
234 else:
235 func = cast(core_schema.NoInfoValidatorFunction, self.func) 1gabjklhcdmnoiefpqr
236 return core_schema.no_info_plain_validator_function( 1gabjklhcdmnoiefpqr
237 func,
238 serialization=serialization, # pyright: ignore[reportArgumentType]
239 json_schema_input_schema=input_schema,
240 )
242 @classmethod 1gabjklhcdmnosiefpqr
243 def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self: 1gabjklhcdmnosiefpqr
244 return cls( 1gabjklhcdmnoiefpqr
245 func=decorator.func,
246 json_schema_input_type=decorator.info.json_schema_input_type,
247 )
250@dataclasses.dataclass(frozen=True, slots=True) 1gabjklhcdmnosiefpqr
251class WrapValidator: 1gabjklhcdmnosiefpqr
252 """!!! abstract "Usage Documentation"
253 [field *wrap* validators](../concepts/validators.md#field-wrap-validator)
255 A metadata class that indicates that a validation should be applied **around** the inner validation logic.
257 Attributes:
258 func: The validator function.
259 json_schema_input_type: The input type used to generate the appropriate
260 JSON Schema (in validation mode). The actual input type is `Any`.
262 ```python
263 from datetime import datetime
264 from typing import Annotated
266 from pydantic import BaseModel, ValidationError, WrapValidator
268 def validate_timestamp(v, handler):
269 if v == 'now':
270 # we don't want to bother with further validation, just return the new value
271 return datetime.now()
272 try:
273 return handler(v)
274 except ValidationError:
275 # validation failed, in this case we want to return a default value
276 return datetime(2000, 1, 1)
278 MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)]
280 class Model(BaseModel):
281 a: MyTimestamp
283 print(Model(a='now').a)
284 #> 2032-01-02 03:04:05.000006
285 print(Model(a='invalid').a)
286 #> 2000-01-01 00:00:00
287 ```
288 """
290 func: core_schema.NoInfoWrapValidatorFunction | core_schema.WithInfoWrapValidatorFunction 1gabjklhcdmnosiefpqr
291 json_schema_input_type: Any = PydanticUndefined 1gabjklhcdmnosiefpqr
293 def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1gabjklhcdmnosiefpqr
294 schema = handler(source_type) 1gabjklhcdmnoiefpqr
295 input_schema = ( 1gabjklhcdmnoiefpqr
296 None
297 if self.json_schema_input_type is PydanticUndefined
298 else handler.generate_schema(self.json_schema_input_type)
299 )
301 info_arg = _inspect_validator(self.func, mode='wrap', type='field') 1gabjklhcdmnoiefpqr
302 if info_arg: 1gabjklhcdmnoiefpqr
303 func = cast(core_schema.WithInfoWrapValidatorFunction, self.func) 1gabjklhcdmnoiefpqr
304 return core_schema.with_info_wrap_validator_function( 1gabjklhcdmnoiefpqr
305 func,
306 schema=schema,
307 json_schema_input_schema=input_schema,
308 )
309 else:
310 func = cast(core_schema.NoInfoWrapValidatorFunction, self.func) 1gabjklhcdmnoiefpqr
311 return core_schema.no_info_wrap_validator_function( 1gabjklhcdmnoiefpqr
312 func,
313 schema=schema,
314 json_schema_input_schema=input_schema,
315 )
317 @classmethod 1gabjklhcdmnosiefpqr
318 def _from_decorator(cls, decorator: _decorators.Decorator[_decorators.FieldValidatorDecoratorInfo]) -> Self: 1gabjklhcdmnosiefpqr
319 return cls( 1gabjklhcdmnoiefpqr
320 func=decorator.func,
321 json_schema_input_type=decorator.info.json_schema_input_type,
322 )
325if TYPE_CHECKING: 1gabjklhcdmnosiefpqr
327 class _OnlyValueValidatorClsMethod(Protocol):
328 def __call__(self, cls: Any, value: Any, /) -> Any: ...
330 class _V2ValidatorClsMethod(Protocol):
331 def __call__(self, cls: Any, value: Any, info: core_schema.ValidationInfo[Any], /) -> Any: ...
333 class _OnlyValueWrapValidatorClsMethod(Protocol):
334 def __call__(self, cls: Any, value: Any, handler: core_schema.ValidatorFunctionWrapHandler, /) -> Any: ...
336 class _V2WrapValidatorClsMethod(Protocol):
337 def __call__(
338 self,
339 cls: Any,
340 value: Any,
341 handler: core_schema.ValidatorFunctionWrapHandler,
342 info: core_schema.ValidationInfo[Any],
343 /,
344 ) -> Any: ...
346 _V2Validator: TypeAlias = (
347 _V2ValidatorClsMethod
348 | core_schema.WithInfoValidatorFunction
349 | _OnlyValueValidatorClsMethod
350 | core_schema.NoInfoValidatorFunction
351 )
353 _V2WrapValidator: TypeAlias = (
354 _V2WrapValidatorClsMethod
355 | core_schema.WithInfoWrapValidatorFunction
356 | _OnlyValueWrapValidatorClsMethod
357 | core_schema.NoInfoWrapValidatorFunction
358 )
360 _PartialClsOrStaticMethod: TypeAlias = classmethod[Any, Any, Any] | staticmethod[Any, Any] | partialmethod[Any]
362 _V2BeforeAfterOrPlainValidatorType = TypeVar(
363 '_V2BeforeAfterOrPlainValidatorType',
364 bound=_V2Validator | _PartialClsOrStaticMethod,
365 )
366 _V2WrapValidatorType = TypeVar('_V2WrapValidatorType', bound=_V2WrapValidator | _PartialClsOrStaticMethod)
368FieldValidatorModes: TypeAlias = Literal['before', 'after', 'wrap', 'plain'] 1gabjklhcdmnosiefpqr
371@overload 1gabjklhcdmnosiefpqr
372def field_validator( 1gabjklhcdmnosiefpqr
373 field: str, 1abcdsef
374 /,
375 *fields: str, 1abcdsef
376 mode: Literal['wrap'], 1abcdsef
377 check_fields: bool | None = ..., 1gabjklhcdmnosiefpqr
378 json_schema_input_type: Any = ..., 1gabjklhcdmnosiefpqr
379) -> Callable[[_V2WrapValidatorType], _V2WrapValidatorType]: ... 1abcdsef
382@overload 1gabjklhcdmnosiefpqr
383def field_validator( 1gabjklhcdmnosiefpqr
384 field: str, 1abcdsef
385 /,
386 *fields: str, 1abcdsef
387 mode: Literal['before', 'plain'], 1abcdsef
388 check_fields: bool | None = ..., 1gabjklhcdmnosiefpqr
389 json_schema_input_type: Any = ..., 1gabjklhcdmnosiefpqr
390) -> Callable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]: ... 1abcdsef
393@overload 1gabjklhcdmnosiefpqr
394def field_validator( 1gabjklhcdmnosiefpqr
395 field: str, 1abcdsef
396 /,
397 *fields: str, 1abcdsef
398 mode: Literal['after'] = ..., 1gabjklhcdmnosiefpqr
399 check_fields: bool | None = ..., 1gabjklhcdmnosiefpqr
400) -> Callable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]: ... 1abcdsef
403def field_validator( # noqa: D417 1gabjklhcdmnosiefpqr
404 field: str,
405 /,
406 *fields: str,
407 mode: FieldValidatorModes = 'after',
408 check_fields: bool | None = None,
409 json_schema_input_type: Any = PydanticUndefined,
410) -> Callable[[Any], Any]:
411 """!!! abstract "Usage Documentation"
412 [field validators](../concepts/validators.md#field-validators)
414 Decorate methods on the class indicating that they should be used to validate fields.
416 Example usage:
417 ```python
418 from typing import Any
420 from pydantic import (
421 BaseModel,
422 ValidationError,
423 field_validator,
424 )
426 class Model(BaseModel):
427 a: str
429 @field_validator('a')
430 @classmethod
431 def ensure_foobar(cls, v: Any):
432 if 'foobar' not in v:
433 raise ValueError('"foobar" not found in a')
434 return v
436 print(repr(Model(a='this is foobar good')))
437 #> Model(a='this is foobar good')
439 try:
440 Model(a='snap')
441 except ValidationError as exc_info:
442 print(exc_info)
443 '''
444 1 validation error for Model
445 a
446 Value error, "foobar" not found in a [type=value_error, input_value='snap', input_type=str]
447 '''
448 ```
450 For more in depth examples, see [Field Validators](../concepts/validators.md#field-validators).
452 Errors raised in a field validator become part of the model's
453 [`ValidationError`][pydantic_core.ValidationError]. In a running application,
454 [Logfire](../integrations/logfire.md) can record the input each failed validation rejected — see
455 [Troubleshooting validation errors](../errors/troubleshooting.md).
457 Args:
458 *fields: The field names the validator should apply to.
459 mode: Specifies whether to validate the fields before or after validation.
460 check_fields: Whether to check that the fields actually exist on the model.
461 json_schema_input_type: The input type of the function. This is only used to generate
462 the appropriate JSON Schema (in validation mode) and can only specified
463 when `mode` is either `'before'`, `'plain'` or `'wrap'`.
465 Raises:
466 PydanticUserError:
467 - If the decorator is used without any arguments (at least one field name must be provided).
468 - If the provided field names are not strings.
469 - If `json_schema_input_type` is provided with an unsupported `mode`.
470 - If the decorator is applied to an instance method.
471 """
472 if callable(field) or isinstance(field, classmethod): 1gabjklhcdmnosiefpqr
473 raise PydanticUserError( 1gabjklhcdmnoiefpqr
474 'The `@field_validator` decorator cannot be used without arguments, at least one field must be provided. '
475 "For example: `@field_validator('<field_name>', ...)`.",
476 code='decorator-missing-arguments',
477 )
479 if mode not in ('before', 'plain', 'wrap') and json_schema_input_type is not PydanticUndefined: 1gabjklhcdmnosiefpqr
480 raise PydanticUserError( 1gabjklhcdmnoiefpqr
481 f"`json_schema_input_type` can't be used when mode is set to {mode!r}",
482 code='validator-input-type',
483 )
485 if json_schema_input_type is PydanticUndefined and mode == 'plain': 1gabjklhcdmnosiefpqr
486 json_schema_input_type = Any 1gabjklhcdmnoiefpqr
488 fields = field, *fields 1gabjklhcdmnosiefpqr
489 if not all(isinstance(field, str) for field in fields): 1gabjklhcdmnosiefpqr
490 raise PydanticUserError( 1gabjklhcdmnoiefpqr
491 'The provided field names to the `@field_validator` decorator should be strings. '
492 "For example: `@field_validator('<field_name_1>', '<field_name_2>', ...).`",
493 code='decorator-invalid-fields',
494 )
496 def dec( 1gabjklhcdmnosiefpqr
497 f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any],
498 ) -> _decorators.PydanticDescriptorProxy[Any]:
499 if _decorators.is_instance_method_from_sig(f): 1gabjklhcdmnosiefpqr
500 raise PydanticUserError( 1gabjklhcdmnoiefpqr
501 'The `@field_validator` decorator cannot be applied to instance methods',
502 code='validator-instance-method',
503 )
505 # auto apply the @classmethod decorator
506 f = _decorators.ensure_classmethod_based_on_signature(f) 1gabjklhcdmnosiefpqr
508 dec_info = _decorators.FieldValidatorDecoratorInfo( 1gabjklhcdmnosiefpqr
509 fields=fields, mode=mode, check_fields=check_fields, json_schema_input_type=json_schema_input_type
510 )
511 return _decorators.PydanticDescriptorProxy(f, dec_info) 1gabjklhcdmnosiefpqr
513 return dec 1gabjklhcdmnosiefpqr
516_ModelType = TypeVar('_ModelType') 1gabjklhcdmnosiefpqr
517_ModelTypeCo = TypeVar('_ModelTypeCo', covariant=True) 1gabjklhcdmnosiefpqr
520class ModelWrapValidatorHandler(core_schema.ValidatorFunctionWrapHandler, Protocol[_ModelTypeCo]): 1gabjklhcdmnosiefpqr
521 """`@model_validator` decorated function handler argument type. This is used when `mode='wrap'`."""
523 def __call__( # noqa: D102 1gabjklhcdmnosiefpqr
524 self,
525 value: Any, 1abcdsef
526 outer_location: str | int | None = None, 1gabhcdsief
527 /,
528 ) -> _ModelTypeCo: # pragma: no cover 1abcdsef
529 ...
532class ModelWrapValidatorWithoutInfo(Protocol[_ModelType]): 1gabjklhcdmnosiefpqr
533 """A `@model_validator` decorated function signature.
534 This is used when `mode='wrap'` and the function does not have info argument.
535 """
537 def __call__( # noqa: D102 1gabjklhcdmnosiefpqr
538 self,
539 cls: type[_ModelType], 1abcdsef
540 # this can be a dict, a model instance
541 # or anything else that gets passed to validate_python
542 # thus validators _must_ handle all cases
543 value: Any, 1abcdsef
544 handler: ModelWrapValidatorHandler[_ModelType], 1abcdsef
545 /,
546 ) -> _ModelType: ... 1abcdsef
549class ModelWrapValidator(Protocol[_ModelType]): 1gabjklhcdmnosiefpqr
550 """A `@model_validator` decorated function signature. This is used when `mode='wrap'`."""
552 def __call__( # noqa: D102 1gabjklhcdmnosiefpqr
553 self,
554 cls: type[_ModelType], 1abcdsef
555 # this can be a dict, a model instance
556 # or anything else that gets passed to validate_python
557 # thus validators _must_ handle all cases
558 value: Any, 1abcdsef
559 handler: ModelWrapValidatorHandler[_ModelType], 1abcdsef
560 info: core_schema.ValidationInfo, 1abcdsef
561 /,
562 ) -> _ModelType: ... 1abcdsef
565class FreeModelBeforeValidatorWithoutInfo(Protocol): 1gabjklhcdmnosiefpqr
566 """A `@model_validator` decorated function signature. 1gabjklhcdmnosiefpqr
567 This is used when `mode='before'` and the function does not have info argument.
568 """
570 def __call__( # noqa: D102 1gabjklhcdmnosiefpqr
571 self,
572 # this can be a dict, a model instance
573 # or anything else that gets passed to validate_python
574 # thus validators _must_ handle all cases
575 value: Any, 1abcdsef
576 /,
577 ) -> Any: ... 1abcdsef
580class ModelBeforeValidatorWithoutInfo(Protocol): 1gabjklhcdmnosiefpqr
581 """A `@model_validator` decorated function signature. 1gabjklhcdmnosiefpqr
582 This is used when `mode='before'` and the function does not have info argument.
583 """
585 def __call__( # noqa: D102 1gabjklhcdmnosiefpqr
586 self,
587 cls: Any, 1abcdsef
588 # this can be a dict, a model instance
589 # or anything else that gets passed to validate_python
590 # thus validators _must_ handle all cases
591 value: Any, 1abcdsef
592 /,
593 ) -> Any: ... 1abcdsef
596class FreeModelBeforeValidator(Protocol): 1gabjklhcdmnosiefpqr
597 """A `@model_validator` decorated function signature. This is used when `mode='before'`.""" 1gabjklhcdmnosiefpqr
599 def __call__( # noqa: D102 1gabjklhcdmnosiefpqr
600 self,
601 # this can be a dict, a model instance
602 # or anything else that gets passed to validate_python
603 # thus validators _must_ handle all cases
604 value: Any, 1abcdsef
605 info: core_schema.ValidationInfo[Any], 1abcdsef
606 /,
607 ) -> Any: ... 1abcdsef
610class ModelBeforeValidator(Protocol): 1gabjklhcdmnosiefpqr
611 """A `@model_validator` decorated function signature. This is used when `mode='before'`.""" 1gabjklhcdmnosiefpqr
613 def __call__( # noqa: D102 1gabjklhcdmnosiefpqr
614 self,
615 cls: Any, 1abcdsef
616 # this can be a dict, a model instance
617 # or anything else that gets passed to validate_python
618 # thus validators _must_ handle all cases
619 value: Any, 1abcdsef
620 info: core_schema.ValidationInfo[Any], 1abcdsef
621 /,
622 ) -> Any: ... 1abcdsef
625ModelAfterValidatorWithoutInfo: TypeAlias = Callable[[_ModelType], _ModelType] 1gabjklhcdmnosiefpqr
626"""A `@model_validator` decorated function signature. This is used when `mode='after'` and the function does not 1gabjklhcdmnosiefpqr
627have info argument.
628"""
630ModelAfterValidator: TypeAlias = Callable[[_ModelType, core_schema.ValidationInfo[Any]], _ModelType] 1gabjklhcdmnosiefpqr
631"""A `@model_validator` decorated function signature. This is used when `mode='after'`.""" 1gabjklhcdmnosiefpqr
633_AnyModelWrapValidator: TypeAlias = ModelWrapValidator[_ModelType] | ModelWrapValidatorWithoutInfo[_ModelType] 1gabjklhcdmnosiefpqr
634_AnyModelBeforeValidator: TypeAlias = ( 1gabjklhcdmnosiefpqr
635 FreeModelBeforeValidator
636 | ModelBeforeValidator
637 | FreeModelBeforeValidatorWithoutInfo
638 | ModelBeforeValidatorWithoutInfo
639)
640_AnyModelAfterValidator: TypeAlias = ModelAfterValidator[_ModelType] | ModelAfterValidatorWithoutInfo[_ModelType] 1gabjklhcdmnosiefpqr
643@overload 1gabjklhcdmnosiefpqr
644def model_validator( 1gabjklhcdmnosiefpqr
645 *,
646 mode: Literal['wrap'], 1abcdsef
647) -> Callable[ 1abcdsef
648 [_AnyModelWrapValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
649]: ...
652@overload 1gabjklhcdmnosiefpqr
653def model_validator( 1gabjklhcdmnosiefpqr
654 *,
655 mode: Literal['before'], 1abcdsef
656) -> Callable[ 1abcdsef
657 [_AnyModelBeforeValidator], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
658]: ...
661@overload 1gabjklhcdmnosiefpqr
662def model_validator( 1gabjklhcdmnosiefpqr
663 *,
664 mode: Literal['after'], 1abcdsef
665) -> Callable[ 1abcdsef
666 [_AnyModelAfterValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]
667]: ...
670def model_validator( 1gabjklhcdmnosiefpqr
671 *,
672 mode: Literal['wrap', 'before', 'after'],
673) -> Any:
674 """!!! abstract "Usage Documentation"
675 [Model Validators](../concepts/validators.md#model-validators)
677 Decorate model methods for validation purposes.
679 Example usage:
680 ```python
681 from typing import Self
683 from pydantic import BaseModel, ValidationError, model_validator
685 class Square(BaseModel):
686 width: float
687 height: float
689 @model_validator(mode='after')
690 def verify_square(self) -> Self:
691 if self.width != self.height:
692 raise ValueError('width and height do not match')
693 return self
695 s = Square(width=1, height=1)
696 print(repr(s))
697 #> Square(width=1.0, height=1.0)
699 try:
700 Square(width=1, height=2)
701 except ValidationError as e:
702 print(e)
703 '''
704 1 validation error for Square
705 Value error, width and height do not match [type=value_error, input_value={'width': 1, 'height': 2}, input_type=dict]
706 '''
707 ```
709 For more in depth examples, see [Model Validators](../concepts/validators.md#model-validators).
711 Cross-field rules like the one above tend to fail on combinations of values you didn't anticipate.
712 The resulting [`ValidationError`][pydantic_core.ValidationError] includes the input that failed;
713 [Logfire](../integrations/logfire.md) can retain these failures with their trace context so you can
714 investigate patterns in a running application (see
715 [Troubleshooting validation errors](../errors/troubleshooting.md)).
717 Args:
718 mode: A required string literal that specifies the validation mode.
719 It can be one of the following: 'wrap', 'before', or 'after'.
721 Returns:
722 A decorator that can be used to decorate a function to be used as a model validator.
723 """
725 def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]: 1gabjklhcdmnoiefpqr
726 if mode == 'after': 1gabjklhcdmnoiefpqr
727 if isinstance( 1gabjklhcdmnoiefpqr
728 _decorators.unwrap_wrapped_function(f, unwrap_class_static_method=False), classmethod
729 ) or _decorators._is_classmethod_from_sig(f):
730 raise PydanticUserError( 1gabjklhcdmnoiefpqr
731 "`@model_validator` with mode='after' must be applied on an instance method, not a class method.",
732 code='model-after-validator-classmethod',
733 )
734 else:
735 # auto apply the @classmethod decorator:
736 f = _decorators.ensure_classmethod_based_on_signature(f) 1gabjklhcdmnoiefpqr
738 dec_info = _decorators.ModelValidatorDecoratorInfo(mode=mode) 1gabjklhcdmnoiefpqr
739 return _decorators.PydanticDescriptorProxy(f, dec_info) 1gabjklhcdmnoiefpqr
741 return dec 1gabjklhcdmnoiefpqr
744AnyType = TypeVar('AnyType') 1gabjklhcdmnosiefpqr
747if TYPE_CHECKING: 1gabjklhcdmnosiefpqr
748 # If we add configurable attributes to IsInstance, we'd probably need to stop hiding it from type checkers like this
749 InstanceOf = Annotated[AnyType, ...] # `IsInstance[Sequence]` will be recognized by type checkers as `Sequence`
751else:
753 @dataclasses.dataclass(slots=True) 1gabjklhcdmnosiefpqr
754 class InstanceOf: 1gabjklhcdmnosiefpqr
755 '''Generic type for annotating a type that is an instance of a given class. 1gabjklhcdmnosiefpqr
757 Example:
758 ```python
759 from pydantic import BaseModel, InstanceOf
761 class Foo:
762 ...
764 class Bar(BaseModel):
765 foo: InstanceOf[Foo]
767 Bar(foo=Foo())
768 try:
769 Bar(foo=42)
770 except ValidationError as e:
771 print(e)
772 """
773 [
774 │ {
775 │ │ 'type': 'is_instance_of',
776 │ │ 'loc': ('foo',),
777 │ │ 'msg': 'Input should be an instance of Foo',
778 │ │ 'input': 42,
779 │ │ 'ctx': {'class': 'Foo'},
780 │ │ 'url': 'https://errors.pydantic.dev/0.38.0/v/is_instance_of'
781 │ }
782 ]
783 """
784 ```
785 '''
787 @classmethod 1gabjklhcdmnosiefpqr
788 def __class_getitem__(cls, item: AnyType) -> AnyType: 1gabjklhcdmnosiefpqr
789 return Annotated[item, cls()] 1gabjklhcdmnoiefpqr
791 @classmethod 1gabjklhcdmnosiefpqr
792 def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1gabjklhcdmnosiefpqr
793 # Lazy import to avoid cycle:
794 from pydantic._internal._generate_schema import GENERATE_SCHEMA_ERRORS 1gabjklhcdmnoiefpqr
796 # use the generic _origin_ as the second argument to isinstance when appropriate
797 instance_of_schema = core_schema.is_instance_schema(_generics.get_origin(source) or source) 1gabjklhcdmnoiefpqr
799 try: 1gabjklhcdmnoiefpqr
800 # Try to generate the "standard" schema, which will be used when loading from JSON
801 original_schema = handler(source) 1gabjklhcdmnoiefpqr
802 except GENERATE_SCHEMA_ERRORS: 1gabjklhcdmnoiefpqr
803 # If that fails, just produce a schema that can validate from python
804 return instance_of_schema 1gabjklhcdmnoiefpqr
805 else:
806 # Use the "original" approach to serialization
807 instance_of_schema['serialization'] = core_schema.wrap_serializer_function_ser_schema( 1gabjklhcdmnoiefpqr
808 function=lambda v, h: h(v), schema=original_schema
809 )
810 return core_schema.json_or_python_schema(python_schema=instance_of_schema, json_schema=original_schema) 1gabjklhcdmnoiefpqr
812 __hash__ = object.__hash__ 1gabjklhcdmnosiefpqr
815if TYPE_CHECKING: 1gabjklhcdmnosiefpqr
816 SkipValidation = Annotated[AnyType, ...] # SkipValidation[list[str]] will be treated by type checkers as list[str]
817else:
819 @dataclasses.dataclass(slots=True) 1gabjklhcdmnosiefpqr
820 class SkipValidation: 1gabjklhcdmnosiefpqr
821 """If this is applied as an annotation (e.g., via `x: Annotated[int, SkipValidation]`), validation will be
822 skipped. You can also use `SkipValidation[int]` as a shorthand for `Annotated[int, SkipValidation]`.
824 This can be useful if you want to use a type annotation for documentation/IDE/type-checking purposes,
825 and know that it is safe to skip validation for one or more of the fields.
827 Because this converts the validation schema to `any_schema`, subsequent annotation-applied transformations
828 may not have the expected effects. Therefore, when used, this annotation should generally be the final
829 annotation applied to a type.
830 """
832 def __class_getitem__(cls, item: Any) -> Any: 1gabjklhcdmnosiefpqr
833 return Annotated[item, SkipValidation()] 1gabjklhcdmnoiefpqr
835 @classmethod 1gabjklhcdmnosiefpqr
836 def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1gabjklhcdmnosiefpqr
837 with warnings.catch_warnings(): 1gabjklhcdmnoiefpqr
838 warnings.simplefilter('ignore', ArbitraryTypeWarning) 1gabjklhcdmnoiefpqr
839 original_schema = handler(source) 1gabjklhcdmnoiefpqr
840 metadata = {'pydantic_js_annotation_functions': [lambda _c, h: h(original_schema)]} 1gabjklhcdmnoiefpqr
841 return core_schema.any_schema( 1gabjklhcdmnoiefpqr
842 metadata=metadata,
843 serialization=core_schema.wrap_serializer_function_ser_schema(
844 function=lambda v, h: h(v), schema=original_schema
845 ),
846 )
848 __hash__ = object.__hash__ 1gabjklhcdmnosiefpqr
851_FromTypeT = TypeVar('_FromTypeT') 1gabjklhcdmnosiefpqr
854class ValidateAs: 1gabjklhcdmnosiefpqr
855 """A helper class to validate a custom type from a type that is natively supported by Pydantic.
857 Args:
858 from_type: The type natively supported by Pydantic to use to perform validation.
859 instantiation_hook: A callable taking the validated type as an argument, and returning
860 the populated custom type.
862 Example:
863 ```python {lint="skip"}
864 from typing import Annotated
866 from pydantic import BaseModel, TypeAdapter, ValidateAs
868 class MyCls:
869 def __init__(self, a: int) -> None:
870 self.a = a
872 def __repr__(self) -> str:
873 return f"MyCls(a={self.a})"
875 class Model(BaseModel):
876 a: int
879 ta = TypeAdapter(
880 Annotated[MyCls, ValidateAs(Model, lambda v: MyCls(a=v.a))]
881 )
883 print(ta.validate_python({'a': 1}))
884 #> MyCls(a=1)
885 ```
886 """
888 def __init__(self, from_type: TypeForm[_FromTypeT], /, instantiation_hook: Callable[[_FromTypeT], Any]) -> None: 1gabjklhcdmnosiefpqr
889 self.from_type = from_type 1gabjklhcdmnoiefpqr
890 self.instantiation_hook = instantiation_hook 1gabjklhcdmnoiefpqr
892 def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: 1gabjklhcdmnosiefpqr
893 # Lazy import to avoid cycle:
894 from pydantic._internal._generate_schema import GENERATE_SCHEMA_ERRORS 1gabjklhcdmnoiefpqr
896 from_type_schema = handler(self.from_type) 1gabjklhcdmnoiefpqr
897 schema = core_schema.no_info_after_validator_function( 1gabjklhcdmnoiefpqr
898 self.instantiation_hook,
899 schema=from_type_schema,
900 )
901 try: 1gabjklhcdmnoiefpqr
902 ser_schema = handler(source) 1gabjklhcdmnoiefpqr
903 except GENERATE_SCHEMA_ERRORS: 1gabjklhcdmnoiefpqr
904 ser_schema = core_schema.any_schema() 1gabjklhcdmnoiefpqr
906 # TODO: pydantic-core now accepts an arbitrary core schema for serialization, so the
907 # wrap serializer workaround below can be replaced with
908 # `schema['serialization'] = _core_utils.as_ser_schema(ser_schema)`.
909 # The same workaround is used in other parts of the code base, so grep for similar cases when fixing:
910 schema['serialization'] = core_schema.wrap_serializer_function_ser_schema( 1gabjklhcdmnoiefpqr
911 function=lambda v, h: h(v), schema=ser_schema
912 )
913 return schema 1gabjklhcdmnoiefpqr