Skip to content

Decorators

plateforme.core.schema.decorators

This module provides utilities for managing schema decorators within the Plateforme framework using Pydantic features.

PlainSerializer dataclass

PlainSerializer(
    func: SerializerFunction,
    return_type: Any = PydanticUndefined,
    when_used: Literal[
        "always", "unless-none", "json", "json-unless-none"
    ] = "always",
)

Plain serializers use a function to modify the output of serialization.

This is particularly helpful when you want to customize the serialization for annotated types. Consider an input of list, which will be serialized into a space-delimited string.

from typing import List

from typing_extensions import Annotated

from pydantic import BaseModel, PlainSerializer

CustomStr = Annotated[
    List, PlainSerializer(lambda x: ' '.join(x), return_type=str)
]

class StudentModel(BaseModel):
    courses: CustomStr

student = StudentModel(courses=['Math', 'Chemistry', 'English'])
print(student.model_dump())
#> {'courses': 'Math Chemistry English'}

Attributes:

Name Type Description
func SerializerFunction

The serializer function.

return_type Any

The return type for the function. If omitted it will be inferred from the type annotation.

when_used Literal['always', 'unless-none', 'json', 'json-unless-none']

Determines when this serializer should be used. Accepts a string with values 'always', 'unless-none', 'json', and 'json-unless-none'. Defaults to 'always'.

WrapSerializer dataclass

WrapSerializer(
    func: WrapSerializerFunction,
    return_type: Any = PydanticUndefined,
    when_used: Literal[
        "always", "unless-none", "json", "json-unless-none"
    ] = "always",
)

Wrap serializers receive the raw inputs along with a handler function that applies the standard serialization logic, and can modify the resulting value before returning it as the final output of serialization.

For example, here's a scenario in which a wrap serializer transforms timezones to UTC and utilizes the existing datetime serialization logic.

from datetime import datetime, timezone
from typing import Any, Dict

from typing_extensions import Annotated

from pydantic import BaseModel, WrapSerializer

class EventDatetime(BaseModel):
    start: datetime
    end: datetime

def convert_to_utc(value: Any, handler, info) -> Dict[str, datetime]:
    # Note that `helper` can actually help serialize the `value` for further custom serialization in case it's a subclass.
    partial_result = handler(value, info)
    if info.mode == 'json':
        return {
            k: datetime.fromisoformat(v).astimezone(timezone.utc)
            for k, v in partial_result.items()
        }
    return {k: v.astimezone(timezone.utc) for k, v in partial_result.items()}

UTCEventDatetime = Annotated[EventDatetime, WrapSerializer(convert_to_utc)]

class EventModel(BaseModel):
    event_datetime: UTCEventDatetime

dt = EventDatetime(
    start='2024-01-01T07:00:00-08:00', end='2024-01-03T20:00:00+06:00'
)
event = EventModel(event_datetime=dt)
print(event.model_dump())
'''
{
    'event_datetime': {
        'start': datetime.datetime(
            2024, 1, 1, 15, 0, tzinfo=datetime.timezone.utc
        ),
        'end': datetime.datetime(
            2024, 1, 3, 14, 0, tzinfo=datetime.timezone.utc
        ),
    }
}
'''

print(event.model_dump_json())
'''
{"event_datetime":{"start":"2024-01-01T15:00:00Z","end":"2024-01-03T14:00:00Z"}}
'''

Attributes:

Name Type Description
func WrapSerializerFunction

The serializer function to be wrapped.

return_type Any

The return type for the function. If omitted it will be inferred from the type annotation.

when_used Literal['always', 'unless-none', 'json', 'json-unless-none']

Determines when this serializer should be used. Accepts a string with values 'always', 'unless-none', 'json', and 'json-unless-none'. Defaults to 'always'.

AfterValidator dataclass

AfterValidator(
    func: NoInfoValidatorFunction
    | WithInfoValidatorFunction,
)

Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#annotated-validators

A metadata class that indicates that a validation should be applied after the inner validation logic.

Attributes:

Name Type Description
func NoInfoValidatorFunction | WithInfoValidatorFunction

The validator function.

Example
from typing_extensions 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"
      }
    ]
    '''

BeforeValidator dataclass

BeforeValidator(
    func: NoInfoValidatorFunction
    | WithInfoValidatorFunction,
)

Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#annotated-validators

A metadata class that indicates that a validation should be applied before the inner validation logic.

Attributes:

Name Type Description
func NoInfoValidatorFunction | WithInfoValidatorFunction

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

InstanceOf dataclass

InstanceOf()

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'
    │   }
    ]
    """

PlainValidator dataclass

PlainValidator(
    func: NoInfoValidatorFunction
    | WithInfoValidatorFunction,
)

Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#annotated-validators

A metadata class that indicates that a validation should be applied instead of the inner validation logic.

Attributes:

Name Type Description
func NoInfoValidatorFunction | WithInfoValidatorFunction

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

SkipValidation dataclass

SkipValidation()

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.

WrapValidator dataclass

WrapValidator(
    func: NoInfoWrapValidatorFunction
    | WithInfoWrapValidatorFunction,
)

Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#annotated-validators

A metadata class that indicates that a validation should be applied around the inner validation logic.

Attributes:

Name Type Description
func NoInfoWrapValidatorFunction | WithInfoWrapValidatorFunction

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

RecursiveGuard

RecursiveGuard(
    value: str | None = None,
    *,
    mode: Literal["lax", "omit", "raise"] = "raise",
)

A recursive guard for schema validation in model field annotations.

Initialize the recursive guard.

Parameters:

Name Type Description Default
value str | None

The value to add to the recursion context. If set to None, the recursion context is not modified when available. Defaults to None.

None
mode Literal['lax', 'omit', 'raise']

The mode for handling recursion errors. It can be either: - 'lax': Validate leniently the source value even when a recursion loop is detected, and omit only for recursion validation errors, i.e. when the same instance is visited twice. - 'omit': Skip the validation and omit the source value. - 'raise': Raise a validation error when a recursion loop is detected, or when the same instance is visited twice. Defaults to 'raise'.

'raise'
Source code in .venv/lib/python3.12/site-packages/plateforme/core/schema/decorators.py
def __init__(
    self,
    value: str | None = None,
    *,
    mode: Literal['lax', 'omit', 'raise'] = 'raise',
) -> None:
    """Initialize the recursive guard.

    Args:
        value: The value to add to the recursion context. If set to
            ``None``, the recursion context is not modified when available.
            Defaults to ``None``.
        mode: The mode for handling recursion errors. It can be either:
            - ``'lax'``: Validate leniently the source value even when a
                recursion loop is detected, and omit only for recursion
                validation errors, i.e. when the same instance is visited
                twice.
            - ``'omit'``: Skip the validation and omit the source value.
            - ``'raise'``: Raise a validation error when a recursion loop
                is detected, or when the same instance is visited twice.
            Defaults to ``'raise'``.
    """
    self.value = value
    self.mode = mode

field_serializer

field_serializer(
    __field: str,
    *fields: str,
    return_type: Any = ...,
    when_used: Literal[
        "always", "unless-none", "json", "json-unless-none"
    ] = ...,
    check_fields: bool | None = ...,
) -> Callable[
    [_PlainSerializeMethodType], _PlainSerializeMethodType
]
field_serializer(
    __field: str,
    *fields: str,
    mode: Literal["plain"],
    return_type: Any = ...,
    when_used: Literal[
        "always", "unless-none", "json", "json-unless-none"
    ] = ...,
    check_fields: bool | None = ...,
) -> Callable[
    [_PlainSerializeMethodType], _PlainSerializeMethodType
]
field_serializer(
    __field: str,
    *fields: str,
    mode: Literal["wrap"],
    return_type: Any = ...,
    when_used: Literal[
        "always", "unless-none", "json", "json-unless-none"
    ] = ...,
    check_fields: bool | None = ...,
) -> Callable[
    [_WrapSerializeMethodType], _WrapSerializeMethodType
]
field_serializer(
    *fields: str,
    mode: Literal["plain", "wrap"] = "plain",
    return_type: Any = PydanticUndefined,
    when_used: Literal[
        "always", "unless-none", "json", "json-unless-none"
    ] = "always",
    check_fields: bool | None = None,
) -> Callable[[Any], Any]

Decorator that enables custom field serialization.

In the below example, a field of type set is used to mitigate duplication. A field_serializer is used to serialize the data as a sorted list.

from typing import Set

from pydantic import BaseModel, field_serializer

class StudentModel(BaseModel):
    name: str = 'Jane'
    courses: Set[str]

    @field_serializer('courses', when_used='json')
    def serialize_courses_in_order(courses: Set[str]):
        return sorted(courses)

student = StudentModel(courses={'Math', 'Chemistry', 'English'})
print(student.model_dump_json())
#> {"name":"Jane","courses":["Chemistry","English","Math"]}

See Custom serializers for more information.

Four signatures are supported:

  • (self, value: Any, info: FieldSerializationInfo)
  • (self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)
  • (value: Any, info: SerializationInfo)
  • (value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)

Parameters:

Name Type Description Default
fields str

Which field(s) the method should be called on.

()
mode Literal['plain', 'wrap']

The serialization mode.

  • plain means the function will be called instead of the default serialization logic,
  • wrap means the function will be called with an argument to optionally call the default serialization logic.
'plain'
return_type Any

Optional return type for the function, if omitted it will be inferred from the type annotation.

PydanticUndefined
when_used Literal['always', 'unless-none', 'json', 'json-unless-none']

Determines the serializer will be used for serialization.

'always'
check_fields bool | None

Whether to check that the fields actually exist on the model.

None

Returns:

Type Description
Callable[[Any], Any]

The decorator function.

Source code in .venv/lib/python3.12/site-packages/pydantic/functional_serializers.py
def field_serializer(
    *fields: str,
    mode: Literal['plain', 'wrap'] = 'plain',
    return_type: Any = PydanticUndefined,
    when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always',
    check_fields: bool | None = None,
) -> Callable[[Any], Any]:
    """Decorator that enables custom field serialization.

    In the below example, a field of type `set` is used to mitigate duplication. A `field_serializer` is used to serialize the data as a sorted list.

    ```python
    from typing import Set

    from pydantic import BaseModel, field_serializer

    class StudentModel(BaseModel):
        name: str = 'Jane'
        courses: Set[str]

        @field_serializer('courses', when_used='json')
        def serialize_courses_in_order(courses: Set[str]):
            return sorted(courses)

    student = StudentModel(courses={'Math', 'Chemistry', 'English'})
    print(student.model_dump_json())
    #> {"name":"Jane","courses":["Chemistry","English","Math"]}
    ```

    See [Custom serializers](../concepts/serialization.md#custom-serializers) for more information.

    Four signatures are supported:

    - `(self, value: Any, info: FieldSerializationInfo)`
    - `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)`
    - `(value: Any, info: SerializationInfo)`
    - `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)`

    Args:
        fields: Which field(s) the method should be called on.
        mode: The serialization mode.

            - `plain` means the function will be called instead of the default serialization logic,
            - `wrap` means the function will be called with an argument to optionally call the
               default serialization logic.
        return_type: Optional return type for the function, if omitted it will be inferred from the type annotation.
        when_used: Determines the serializer will be used for serialization.
        check_fields: Whether to check that the fields actually exist on the model.

    Returns:
        The decorator function.
    """

    def dec(
        f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any],
    ) -> _decorators.PydanticDescriptorProxy[Any]:
        dec_info = _decorators.FieldSerializerDecoratorInfo(
            fields=fields,
            mode=mode,
            return_type=return_type,
            when_used=when_used,
            check_fields=check_fields,
        )
        return _decorators.PydanticDescriptorProxy(f, dec_info)

    return dec

model_serializer

model_serializer(__f: FuncType) -> FuncType
model_serializer(
    *,
    mode: Literal["plain", "wrap"] = ...,
    when_used: Literal[
        "always", "unless-none", "json", "json-unless-none"
    ] = "always",
    return_type: Any = ...,
) -> Callable[[FuncType], FuncType]
model_serializer(
    __f: Callable[..., Any] | None = None,
    *,
    mode: Literal["plain", "wrap"] = "plain",
    when_used: Literal[
        "always", "unless-none", "json", "json-unless-none"
    ] = "always",
    return_type: Any = PydanticUndefined,
) -> Callable[[Any], Any]

Decorator that enables custom model serialization.

This is useful when a model need to be serialized in a customized manner, allowing for flexibility beyond just specific fields.

An example would be to serialize temperature to the same temperature scale, such as degrees Celsius.

from typing import Literal

from pydantic import BaseModel, model_serializer

class TemperatureModel(BaseModel):
    unit: Literal['C', 'F']
    value: int

    @model_serializer()
    def serialize_model(self):
        if self.unit == 'F':
            return {'unit': 'C', 'value': int((self.value - 32) / 1.8)}
        return {'unit': self.unit, 'value': self.value}

temperature = TemperatureModel(unit='F', value=212)
print(temperature.model_dump())
#> {'unit': 'C', 'value': 100}

See Custom serializers for more information.

Parameters:

Name Type Description Default
__f Callable[..., Any] | None

The function to be decorated.

None
mode Literal['plain', 'wrap']

The serialization mode.

  • 'plain' means the function will be called instead of the default serialization logic
  • 'wrap' means the function will be called with an argument to optionally call the default serialization logic.
'plain'
when_used Literal['always', 'unless-none', 'json', 'json-unless-none']

Determines when this serializer should be used.

'always'
return_type Any

The return type for the function. If omitted it will be inferred from the type annotation.

PydanticUndefined

Returns:

Type Description
Callable[[Any], Any]

The decorator function.

Source code in .venv/lib/python3.12/site-packages/pydantic/functional_serializers.py
def model_serializer(
    __f: Callable[..., Any] | None = None,
    *,
    mode: Literal['plain', 'wrap'] = 'plain',
    when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always',
    return_type: Any = PydanticUndefined,
) -> Callable[[Any], Any]:
    """Decorator that enables custom model serialization.

    This is useful when a model need to be serialized in a customized manner, allowing for flexibility beyond just specific fields.

    An example would be to serialize temperature to the same temperature scale, such as degrees Celsius.

    ```python
    from typing import Literal

    from pydantic import BaseModel, model_serializer

    class TemperatureModel(BaseModel):
        unit: Literal['C', 'F']
        value: int

        @model_serializer()
        def serialize_model(self):
            if self.unit == 'F':
                return {'unit': 'C', 'value': int((self.value - 32) / 1.8)}
            return {'unit': self.unit, 'value': self.value}

    temperature = TemperatureModel(unit='F', value=212)
    print(temperature.model_dump())
    #> {'unit': 'C', 'value': 100}
    ```

    See [Custom serializers](../concepts/serialization.md#custom-serializers) for more information.

    Args:
        __f: The function to be decorated.
        mode: The serialization mode.

            - `'plain'` means the function will be called instead of the default serialization logic
            - `'wrap'` means the function will be called with an argument to optionally call the default
                serialization logic.
        when_used: Determines when this serializer should be used.
        return_type: The return type for the function. If omitted it will be inferred from the type annotation.

    Returns:
        The decorator function.
    """

    def dec(f: Callable[..., Any]) -> _decorators.PydanticDescriptorProxy[Any]:
        dec_info = _decorators.ModelSerializerDecoratorInfo(mode=mode, return_type=return_type, when_used=when_used)
        return _decorators.PydanticDescriptorProxy(f, dec_info)

    if __f is None:
        return dec
    else:
        return dec(__f)  # type: ignore

field_validator

field_validator(
    __field: str,
    *fields: str,
    mode: Literal["before", "after", "plain"] = ...,
    check_fields: bool | None = ...,
) -> Callable[
    [_V2BeforeAfterOrPlainValidatorType],
    _V2BeforeAfterOrPlainValidatorType,
]
field_validator(
    __field: str,
    *fields: str,
    mode: Literal["wrap"],
    check_fields: bool | None = ...,
) -> Callable[[_V2WrapValidatorType], _V2WrapValidatorType]
field_validator(
    __field: str,
    *fields: str,
    mode: FieldValidatorModes = "after",
    check_fields: bool | None = None,
) -> Callable[[Any], Any]

Usage docs: https://docs.pydantic.dev/2.6/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.

Parameters:

Name Type Description Default
__field str

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.

required
*fields str

Additional field(s) the field_validator should be called on.

()
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
  • If @field_validator is used bare (with no fields).
  • If the args passed to @field_validator as fields are not strings.
  • If @field_validator applied to instance methods.
Source code in .venv/lib/python3.12/site-packages/pydantic/functional_validators.py
def field_validator(
    __field: str,
    *fields: str,
    mode: FieldValidatorModes = 'after',
    check_fields: bool | None = None,
) -> Callable[[Any], Any]:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#field-validators

    Decorate methods on the class indicating that they should be used to validate fields.

    Example usage:
    ```py
    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:
        __field: 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.
        *fields: Additional field(s) the `field_validator` should be called on.
        mode: Specifies whether to validate the fields before or after validation.
        check_fields: Whether to check that the fields actually exist on the model.

    Returns:
        A decorator that can be used to decorate a function to be used as a field_validator.

    Raises:
        PydanticUserError:
            - If `@field_validator` is used bare (with no fields).
            - If the args passed to `@field_validator` as fields are not strings.
            - If `@field_validator` applied to instance methods.
    """
    if isinstance(__field, FunctionType):
        raise PydanticUserError(
            '`@field_validator` should be used with fields and keyword arguments, not bare. '
            "E.g. usage should be `@validator('<field_name>', ...)`",
            code='validator-no-fields',
        )
    fields = __field, *fields
    if not all(isinstance(field, str) for field in fields):
        raise PydanticUserError(
            '`@field_validator` fields should be passed as separate string args. '
            "E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`",
            code='validator-invalid-fields',
        )

    def dec(
        f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any],
    ) -> _decorators.PydanticDescriptorProxy[Any]:
        if _decorators.is_instance_method_from_sig(f):
            raise PydanticUserError(
                '`@field_validator` cannot be applied to instance methods', code='validator-instance-method'
            )

        # auto apply the @classmethod decorator
        f = _decorators.ensure_classmethod_based_on_signature(f)

        dec_info = _decorators.FieldValidatorDecoratorInfo(fields=fields, mode=mode, check_fields=check_fields)
        return _decorators.PydanticDescriptorProxy(f, dec_info)

    return dec

model_validator

model_validator(
    *, mode: Literal["wrap"]
) -> Callable[
    [_AnyModelWrapValidator[_ModelType]],
    PydanticDescriptorProxy[ModelValidatorDecoratorInfo],
]
model_validator(
    *, mode: Literal["before"]
) -> Callable[
    [_AnyModeBeforeValidator],
    PydanticDescriptorProxy[ModelValidatorDecoratorInfo],
]
model_validator(
    *, mode: Literal["after"]
) -> Callable[
    [_AnyModelAfterValidator[_ModelType]],
    PydanticDescriptorProxy[ModelValidatorDecoratorInfo],
]
model_validator(
    *, mode: Literal["wrap", "before", "after"]
) -> Any

Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#model-validators

Decorate model methods for validation purposes.

Example usage:

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.

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 .venv/lib/python3.12/site-packages/pydantic/functional_validators.py
def model_validator(
    *,
    mode: Literal['wrap', 'before', 'after'],
) -> Any:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#model-validators

    Decorate model methods for validation purposes.

    Example usage:
    ```py
    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.
    """

    def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]:
        # auto apply the @classmethod decorator
        f = _decorators.ensure_classmethod_based_on_signature(f)
        dec_info = _decorators.ModelValidatorDecoratorInfo(mode=mode)
        return _decorators.PydanticDescriptorProxy(f, dec_info)

    return dec

validate_call

validate_call(
    *,
    config: ConfigDict | None = None,
    validate_return: bool = False,
) -> Callable[[AnyCallableT], AnyCallableT]
validate_call(__func: AnyCallableT) -> AnyCallableT
validate_call(
    __func: AnyCallableT | None = None,
    *,
    config: ConfigDict | None = None,
    validate_return: bool = False,
) -> AnyCallableT | Callable[[AnyCallableT], AnyCallableT]

Usage docs: https://docs.pydantic.dev/2.6/concepts/validation_decorator/

Returns a decorated wrapper around the function that validates the arguments and, optionally, the return value.

Usage may be either as a plain decorator @validate_call or with arguments @validate_call(...).

Parameters:

Name Type Description Default
__func AnyCallableT | None

The function to be decorated.

None
config ConfigDict | None

The configuration dictionary.

None
validate_return bool

Whether to validate the return value.

False

Returns:

Type Description
AnyCallableT | Callable[[AnyCallableT], AnyCallableT]

The decorated function.

Source code in .venv/lib/python3.12/site-packages/pydantic/validate_call_decorator.py
def validate_call(
    __func: AnyCallableT | None = None,
    *,
    config: ConfigDict | None = None,
    validate_return: bool = False,
) -> AnyCallableT | Callable[[AnyCallableT], AnyCallableT]:
    """Usage docs: https://docs.pydantic.dev/2.6/concepts/validation_decorator/

    Returns a decorated wrapper around the function that validates the arguments and, optionally, the return value.

    Usage may be either as a plain decorator `@validate_call` or with arguments `@validate_call(...)`.

    Args:
        __func: The function to be decorated.
        config: The configuration dictionary.
        validate_return: Whether to validate the return value.

    Returns:
        The decorated function.
    """

    def validate(function: AnyCallableT) -> AnyCallableT:
        if isinstance(function, (classmethod, staticmethod)):
            name = type(function).__name__
            raise TypeError(f'The `@{name}` decorator should be applied after `@validate_call` (put `@{name}` on top)')
        validate_call_wrapper = _validate_call.ValidateCallWrapper(function, config, validate_return)

        @functools.wraps(function)
        def wrapper_function(*args, **kwargs):
            return validate_call_wrapper(*args, **kwargs)

        wrapper_function.raw_function = function  # type: ignore

        return wrapper_function  # type: ignore

    if __func:
        return validate(__func)
    else:
        return validate