Functional Validators
This module contains related classes and functions for validation.
Handler to call into the next CoreSchema schema generation function.
Get the name of the closest field to this validator.
Type: str | None
def __call__(__source_type: Any) -> core_schema.CoreSchema
Call the inner handler and get the CoreSchema it returns.
This will call the next CoreSchema modifying function up until it calls
into Pydantic’s internal schema generation machinery, which will raise a
pydantic.errors.PydanticSchemaGenerationError error if it cannot generate
a CoreSchema for the given source type.
core_schema.CoreSchema — The pydantic-core CoreSchema generated.
The input type.
def generate_schema(__source_type: Any) -> core_schema.CoreSchema
Generate a schema unrelated to the current context.
Use this function if e.g. you are handling schema generation for a sequence
and want to generate a schema for its items.
Otherwise, you may end up doing something like applying a min_length constraint
that was intended for the sequence itself to its items!
core_schema.CoreSchema — The pydantic-core CoreSchema generated.
The input type.
def resolve_ref_schema(
__maybe_ref_schema: core_schema.CoreSchema,
) -> core_schema.CoreSchema
Get the real schema for a definition-ref schema.
If the schema given is not a definition-ref schema, it will be returned as is.
This means you don’t have to check before calling this function.
core_schema.CoreSchema — A concrete CoreSchema.
A CoreSchema, ref-based or not.
LookupError— If therefis not found.
Bases: PydanticErrorMixin, TypeError
An error raised due to incorrect use of Pydantic.
Usage docs: https://docs.pydantic.dev/2.5/concepts/validators/#annotated-validators
A metadata class that indicates that a validation should be applied after the inner validation logic.
Type: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
Usage docs: https://docs.pydantic.dev/2.5/concepts/validators/#annotated-validators
A metadata class that indicates that a validation should be applied before the inner validation logic.
Type: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
Usage docs: https://docs.pydantic.dev/2.5/concepts/validators/#annotated-validators
A metadata class that indicates that a validation should be applied instead of the inner validation logic.
Type: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction
Usage docs: https://docs.pydantic.dev/2.5/concepts/validators/#annotated-validators
A metadata class that indicates that a validation should be applied around the inner validation logic.
from datetime import datetime
from typing_extensions 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
Type: core_schema.NoInfoWrapValidatorFunction | core_schema.WithInfoWrapValidatorFunction
Bases: ValidatorFunctionWrapHandler, Protocol[_ModelTypeCo]
@model_validator decorated function handler argument type. This is used when mode='wrap'.
Bases: Protocol[_ModelType]
A @model_validator decorated function signature.
This is used when mode='wrap' and the function does not have info argument.
Bases: Protocol[_ModelType]
A @model_validator decorated function signature. This is used when mode='wrap'.
Bases: Protocol
A @model_validator decorated function signature.
This is used when mode='before' and the function does not have info argument.
Bases: Protocol
A @model_validator decorated function signature. This is used when mode='before'.
Generic type for annotating a type that is an instance of a given class.
If 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.
def field_validator(
__field: str,
fields: str = (),
mode: Literal['before', 'after', 'plain'] = ...,
check_fields: bool | None = ...,
) -> Callable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]
def field_validator(
__field: str,
fields: str = (),
mode: Literal['wrap'],
check_fields: bool | None = ...,
) -> Callable[[_V2WrapValidatorType], _V2WrapValidatorType]
Usage docs: https://docs.pydantic.dev/2.5/concepts/validators/#field-validators
Decorate methods on the class indicating that they should be used to validate fields.
Example usage:
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.
Callable[[Any], Any] — A decorator that can be used to decorate a function to be used as a field_validator.
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.
Additional field(s) the field_validator should be called on.
Specifies whether to validate the fields before or after validation.
Whether to check that the fields actually exist on the model.
PydanticUserError—- If
@field_validatoris used bare (with no fields). - If the args passed to
@field_validatoras fields are not strings. - If
@field_validatorapplied to instance methods.
def model_validator(
mode: Literal['wrap'],
) -> Callable[[_AnyModelWrapValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]]
def model_validator(
mode: Literal['before'],
) -> Callable[[_AnyModeBeforeValidator], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]]
def model_validator(
mode: Literal['after'],
) -> Callable[[_AnyModelAfterValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo]]
Usage docs: https://docs.pydantic.dev/2.5/concepts/validators/#model-validators
Decorate model methods for validation purposes.
Example usage:
from typing import Optional
from pydantic import BaseModel, ValidationError, model_validator
class Square(BaseModel):
width: float
height: float
@model_validator(mode='after')
def verify_square(self) -> 'Rectangle':
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
__root__
width and height do not match (type=value_error)
'''
For more in depth examples, see Model Validators.
Any — A decorator that can be used to decorate a function to be used as a model validator.
A required string literal that specifies the validation mode. It can be one of the following: ‘wrap’, ‘before’, or ‘after’.
Type: TypeAlias Default: Literal['before', 'after', 'wrap', 'plain']
A @model_validator decorated function signature. This is used when mode='after' and the function does not
have info argument.
Default: Callable[[_ModelType], _ModelType]
A @model_validator decorated function signature. This is used when mode='after'.
Default: Callable[[_ModelType, _core_schema.ValidationInfo], _ModelType]
Default: TypeVar('AnyType')