A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.pydantic.dev/dev/concepts/validators/ below:

Validators - Pydantic Validation

Validators

In addition to Pydantic's built-in validation capabilities, you can leverage custom validators at the field and model levels to enforce more complex constraints and ensure the integrity of your data.

Tip

Want to quickly jump to the relevant validator section?

Field validators API Documentation

pydantic.functional_validators.WrapValidator
pydantic.functional_validators.PlainValidator
pydantic.functional_validators.BeforeValidator
pydantic.functional_validators.AfterValidator
pydantic.functional_validators.field_validator

In its simplest form, a field validator is a callable taking the value to be validated as an argument and returning the validated value. The callable can perform checks for specific conditions (see raising validation errors) and make changes to the validated value (coercion or mutation).

Four different types of validators can be used. They can all be defined using the annotated pattern or using the field_validator() decorator, applied on a class method:

Validation of default values

As mentioned in the fields documentation, default values of fields are not validated unless configured to do so, and thus custom validators will not be applied as well.

Which validator pattern to use

While both approaches can achieve the same thing, each pattern provides different benefits.

Using the annotated pattern

One of the key benefits of using the annotated pattern is to make validators reusable:

from typing import Annotated

from pydantic import AfterValidator, BaseModel


def is_even(value: int) -> int:
    if value % 2 == 1:
        raise ValueError(f'{value} is not an even number')
    return value


EvenNumber = Annotated[int, AfterValidator(is_even)]


class Model1(BaseModel):
    my_number: EvenNumber


class Model2(BaseModel):
    other_number: Annotated[EvenNumber, AfterValidator(lambda v: v + 2)]


class Model3(BaseModel):
    list_of_even_numbers: list[EvenNumber]  # (1)!
  1. As mentioned in the annotated pattern documentation, we can also make use of validators for specific parts of the annotation (in this case, validation is applied for list items, but not the whole list).

It is also easier to understand which validators are applied to a type, by just looking at the field annotation.

Using the decorator pattern

One of the key benefits of using the field_validator() decorator is to apply the function to multiple fields:

from pydantic import BaseModel, field_validator


class Model(BaseModel):
    f1: str
    f2: str

    @field_validator('f1', 'f2', mode='before')
    @classmethod
    def capitalize(cls, value: str) -> str:
        return value.capitalize()

Here are a couple additional notes about the decorator usage:

Model validators API Documentation

pydantic.functional_validators.model_validator

Validation can also be performed on the entire model's data using the model_validator() decorator.

Three different types of model validators can be used:

On inheritance

A model validator defined in a base class will be called during the validation of a subclass instance.

Overriding a model validator in a subclass will override the base class' validator, and thus only the subclass' version of said validator will be called.

Raising validation errors

To raise a validation error, three types of exceptions can be used:

Validation info

Both the field and model validators callables (in all modes) can optionally take an extra ValidationInfo argument, providing useful extra information, such as:

Validation data

For field validators, the already validated data can be accessed using the data property. Here is an example than can be used as an alternative to the after model validator example:

from pydantic import BaseModel, ValidationInfo, field_validator


class UserModel(BaseModel):
    password: str
    password_repeat: str
    username: str

    @field_validator('password_repeat', mode='after')
    @classmethod
    def check_passwords_match(cls, value: str, info: ValidationInfo) -> str:
        if value != info.data['password']:
            raise ValueError('Passwords do not match')
        return value

Warning

As validation is performed in the order fields are defined, you have to make sure you are not accessing a field that hasn't been validated yet. In the code above, for example, the username validated value is not available yet, as it is defined after password_repeat.

The data property is None for model validators.

Validation context

You can pass a context object to the validation methods, which can be accessed inside the validator functions using the context property:

from pydantic import BaseModel, ValidationInfo, field_validator


class Model(BaseModel):
    text: str

    @field_validator('text', mode='after')
    @classmethod
    def remove_stopwords(cls, v: str, info: ValidationInfo) -> str:
        if isinstance(info.context, dict):
            stopwords = info.context.get('stopwords', set())
            v = ' '.join(w for w in v.split() if w.lower() not in stopwords)
        return v


data = {'text': 'This is an example document'}
print(Model.model_validate(data))  # no context
#> text='This is an example document'
print(Model.model_validate(data, context={'stopwords': ['this', 'is', 'an']}))
#> text='example document'

Similarly, you can use a context for serialization.

Providing context when directly instantiating a model

It is currently not possible to provide a context when directly instantiating a model (i.e. when calling Model(...)). You can work around this through the use of a ContextVar and a custom __init__ method:

from __future__ import annotations

from contextlib import contextmanager
from contextvars import ContextVar
from typing import Any, Generator

from pydantic import BaseModel, ValidationInfo, field_validator

_init_context_var = ContextVar('_init_context_var', default=None)


@contextmanager
def init_context(value: dict[str, Any]) -> Generator[None]:
    token = _init_context_var.set(value)
    try:
        yield
    finally:
        _init_context_var.reset(token)


class Model(BaseModel):
    my_number: int

    def __init__(self, /, **data: Any) -> None:
        self.__pydantic_validator__.validate_python(
            data,
            self_instance=self,
            context=_init_context_var.get(),
        )

    @field_validator('my_number')
    @classmethod
    def multiply_with_context(cls, value: int, info: ValidationInfo) -> int:
        if isinstance(info.context, dict):
            multiplier = info.context.get('multiplier', 1)
            value = value * multiplier
        return value


print(Model(my_number=2))
#> my_number=2

with init_context({'multiplier': 3}):
    print(Model(my_number=2))
    #> my_number=6

print(Model(my_number=2))
#> my_number=2
Ordering of validators

When using the annotated pattern, the order in which validators are applied is defined as follows: before and wrap validators are run from right to left, and after validators are then run from left to right:

from pydantic import AfterValidator, BaseModel, BeforeValidator, WrapValidator


class Model(BaseModel):
    name: Annotated[
        str,
        AfterValidator(runs_3rd),
        AfterValidator(runs_4th),
        BeforeValidator(runs_2nd),
        WrapValidator(runs_1st),
    ]

Internally, validators defined using the decorator are converted to their annotated form counterpart and added last after the existing metadata for the field. This means that the same ordering logic applies.

Special types

Pydantic provides a few special utilities that can be used to customize validation.

JSON Schema and field validators

When using before, plain or wrap field validators, the accepted input type may be different from the field annotation.

Consider the following example:

from typing import Any

from pydantic import BaseModel, field_validator


class Model(BaseModel):
    value: str

    @field_validator('value', mode='before')
    @classmethod
    def cast_ints(cls, value: Any) -> Any:
        if isinstance(value, int):
            return str(value)
        else:
            return value


print(Model(value='a'))
#> value='a'
print(Model(value=1))
#> value='1'

While the type hint for value is str, the cast_ints validator also allows integers. To specify the correct input type, the json_schema_input_type argument can be provided:

from typing import Any, Union

from pydantic import BaseModel, field_validator


class Model(BaseModel):
    value: str

    @field_validator(
        'value', mode='before', json_schema_input_type=Union[int, str]
    )
    @classmethod
    def cast_ints(cls, value: Any) -> Any:
        if isinstance(value, int):
            return str(value)
        else:
            return value


print(Model.model_json_schema()['properties']['value'])
#> {'anyOf': [{'type': 'integer'}, {'type': 'string'}], 'title': 'Value'}

As a convenience, Pydantic will use the field type if the argument is not provided (unless you are using a plain validator, in which case json_schema_input_type defaults to Any as the field type is completely discarded).


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4