Functional Validators
This module contains related classes and functions for validation.
ModelAfterValidatorWithoutInfo
module-attribute
¶
ModelAfterValidatorWithoutInfo = Callable[
[_ModelType], _ModelType
]
A @model_validator
decorated function signature. This is used when mode='after'
and the function does not
have info argument.
ModelAfterValidator
module-attribute
¶
ModelAfterValidator = Callable[
[_ModelType, _core_schema.ValidationInfo], _ModelType
]
A @model_validator
decorated function signature. This is used when mode='after'
.
AfterValidator
dataclass
¶
Usage Documentation
A metadata class that indicates that a validation should be applied after the inner validation logic.
Attributes:
Name | Type | Description |
---|---|---|
func |
core_schema.NoInfoValidatorFunction | core_schema.GeneralValidatorFunction
|
The validator function. |
Example
from typing import Annotated
from pydantic import BaseModel, AfterValidator, 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/0.38.0/v/int_parsing"
}
]
"""
BeforeValidator
dataclass
¶
Usage Documentation
A metadata class that indicates that a validation should be applied before the inner validation logic.
Attributes:
Name | Type | Description |
---|---|---|
func |
core_schema.NoInfoValidatorFunction | core_schema.GeneralValidatorFunction
|
The validator function. |
Example
from typing_extensions 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
PlainValidator
dataclass
¶
Usage Documentation
A metadata class that indicates that a validation should be applied instead of the inner validation logic.
Attributes:
Name | Type | Description |
---|---|---|
func |
core_schema.NoInfoValidatorFunction | core_schema.GeneralValidatorFunction
|
The validator function. |
Example
from typing_extensions import Annotated
from pydantic import BaseModel, PlainValidator
MyInt = Annotated[int, PlainValidator(lambda v: int(v) + 1)]
class Model(BaseModel):
a: MyInt
print(Model(a='1').a)
#> 2
WrapValidator
dataclass
¶
Usage Documentation
A metadata class that indicates that a validation should be applied around the inner validation logic.
Attributes:
Name | Type | Description |
---|---|---|
func |
core_schema.NoInfoWrapValidatorFunction | core_schema.GeneralWrapValidatorFunction | core_schema.FieldWrapValidatorFunction
|
The validator function. |
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
ModelWrapValidatorHandler ¶
Bases: _core_schema.ValidatorFunctionWrapHandler
, Protocol[_ModelTypeCo]
@model_validator decorated function handler argument type. This is used when mode='wrap'
.
ModelWrapValidatorWithoutInfo ¶
Bases: Protocol[_ModelType]
A @model_validator decorated function signature.
This is used when mode='wrap'
and the function does not have info argument.
ModelWrapValidator ¶
Bases: Protocol[_ModelType]
A @model_validator decorated function signature. This is used when mode='wrap'
.
ModelBeforeValidatorWithoutInfo ¶
Bases: Protocol
A @model_validator decorated function signature.
This is used when mode='before'
and the function does not have info argument.
ModelBeforeValidator ¶
Bases: Protocol
A @model_validator
decorated function signature. This is used when mode='before'
.
InstanceOf
dataclass
¶
Generic type for annotating a type that is an instance of a given class.
Example
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'
│ }
]
"""
SkipValidation
dataclass
¶
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.
field_validator ¶
field_validator(
__field, *fields, mode="after", check_fields=None
)
Usage Documentation
Decorate methods on the class indicating that they should be used to validate fields.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
__field |
str
|
The first field the |
required |
*fields |
str
|
Additional field(s) the |
()
|
mode |
FieldValidatorModes
|
Specifies whether to validate the fields before or after validation. |
'after'
|
check_fields |
bool | None
|
Whether to check that the fields actually exist on the model. |
None
|
Returns:
Type | Description |
---|---|
Callable[[Any], Any]
|
A decorator that can be used to decorate a function to be used as a field_validator. |
Raises:
Type | Description |
---|---|
PydanticUserError
|
|
Source code in pydantic/functional_validators.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 |
|
model_validator ¶
model_validator(*, mode)
Decorate model methods for validation purposes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mode |
Literal['wrap', 'before', 'after']
|
A required string literal that specifies the validation mode. It can be one of the following: 'wrap', 'before', or 'after'. |
required |
Returns:
Type | Description |
---|---|
Any
|
A decorator that can be used to decorate a function to be used as a model validator. |
Source code in pydantic/functional_validators.py
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 |
|