コンテンツにスキップ

Functional Validators

This module contains related classes and functions for validation.

ModelAfterValidatorWithoutInfo module-attribute

ModelAfterValidatorWithoutInfo = Callable[
    [_ModelType], _ModelType
]

@model_validatorでデコレートされた関数のシグネチャ。これは、mode='after'で、関数にinfo引数がない場合に使用されます。

ModelAfterValidator module-attribute

ModelAfterValidator = Callable[
    [_ModelType, ValidationInfo], _ModelType
]

@model_validatorでデコレートされた関数のシグネチャ。これはmode='after'のときに使用されます。

AfterValidator dataclass

AfterValidator(
    func: (
        NoInfoValidatorFunction | WithInfoValidatorFunction
    ),
)

Usage Documentation

Annotated Validators

内部検証ロジックのに検証を適用する必要があることを示すメタデータクラス。

Attributes:

Name Type Description
func NoInfoValidatorFunction | WithInfoValidatorFunction

バリデーター関数。

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 Documentation

Annotated Validators

内部検証ロジックのに検証を適用する必要があることを示すメタデータクラス。

Attributes:

Name Type Description
func NoInfoValidatorFunction | WithInfoValidatorFunction

バリデーター関数。

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

PlainValidator(
    func: (
        NoInfoValidatorFunction | WithInfoValidatorFunction
    ),
)

Usage Documentation

Annotated Validators

内部検証ロジックの代わりに検証を適用する必要があることを示すメタデータクラス。

Attributes:

Name Type Description
func NoInfoValidatorFunction | WithInfoValidatorFunction

バリデーター関数。

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

WrapValidator(
    func: (
        NoInfoWrapValidatorFunction
        | WithInfoWrapValidatorFunction
    ),
)

Usage Documentation

Annotated Validators

内部検証ロジックの周辺に検証を適用する必要があることを示すメタデータクラス。

Attributes:

Name Type Description
func NoInfoWrapValidatorFunction | WithInfoWrapValidatorFunction

バリデーター関数。

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: ValidatorFunctionWrapHandler, Protocol[_ModelTypeCo]

@model_validatorデコレート関数ハンドラ引数タイプ。これはmode='wrap'のときに使用されます。

ModelWrapValidatorWithoutInfo

Bases: Protocol[_ModelType]

@model_validatorでデコレートされた関数のシグネチャ。 これは、mode='wrap'で関数にinfo引数がない場合に使用されます。

ModelWrapValidator

Bases: Protocol[_ModelType]

@model_validatorでデコレートされた関数のシグネチャ。これはmode='wrap'のときに使用されます。

FreeModelBeforeValidatorWithoutInfo

Bases: Protocol

@model_validatorでデコレートされた関数のシグネチャ。 これは、mode='before'で関数にinfo引数がない場合に使用されます。

ModelBeforeValidatorWithoutInfo

Bases: Protocol

@model_validatorデコレータ関数のシグネチャ。 これは、mode='before'で関数にinfo引数がない場合に使用されます。

FreeModelBeforeValidator

Bases: Protocol

@model_validatorでデコレートされた関数のシグネチャ。これはmode='before'のときに使用されます。

ModelBeforeValidator

Bases: Protocol

@model_validatorでデコレートされた関数のシグネチャ。これはmode='before'のときに使用されます。

InstanceOf dataclass

InstanceOf(__hash__=object.__hash__)

特定のクラスのインスタンスであるタイプに注釈を付けるための汎用タイプ。

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

SkipValidation(__hash__=object.__hash__)

これが注釈として適用される場合(例えば、x:Annotated[int, SkipValidation])、検証はスキップされます。SkipValidation[int]Annotated[int, SkipValidation]の省略形として使用することもできます。

これは、ドキュメント/IDE/型チェックの目的で型アノテーションを使用し、1つ以上のフィールドの検証を省略しても安全であることがわかっている場合に便利です。

これは検証スキーマをany_schemaに変換するので、後続のアノテーション適用変換は期待された効果を持たない可能性があります。したがって、使用される場合、このアノテーションは通常、型に適用される最後のアノテーションである必要があります。

field_validator

field_validator(
    field: str,
    /,
    *fields: str,
    mode: FieldValidatorModes = "after",
    check_fields: bool | None = None,
) -> Callable[[Any], Any]

Usage Documentation

Field validators

クラスのメソッドをデコレートして、フィールドの検証に使用する必要があることを示します。

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]
    '''

詳細な例については、Field Validatorsを参照してください。

Parameters:

Name Type Description Default
field str

field_validatorが呼び出される最初のフィールドです。これはfieldsとは別のもので、少なくとも1つ渡さないとエラーが発生します。

required
*fields str

field_validatorが呼び出される追加フィールドです。

()
mode FieldValidatorModes

検証の前または後にフィールドを検証するかどうかを指定します。

'after'
check_fields bool | None

フィールドがモデル上に実際に存在するかどうかをチェックするかどうか。

None

Returns:

Type Description
Callable[[Any], Any]

field_validatorとして使用する関数を修飾するために使用できるデコレータ。

Raises:

Type Description
PydantictUserError
  • @field_validatorが(フィールドなしで)使用されている場合。
  • フィールドとして@field_validatorに渡された引数が文字列でない場合。
  • @field_validatorがインスタンスメソッドに適用された場合。
Source code in pydantic/functional_validators.py
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def field_validator(
    field: str,
    /,
    *fields: str,
    mode: FieldValidatorModes = 'after',
    check_fields: bool | None = None,
) -> Callable[[Any], Any]:
    """Usage docs: https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/validators/#field-validators

    クラスのメソッドをデコレートして、フィールドの検証に使用する必要があることを示します。

    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]
        '''
    ```

    詳細な例については、[Field Validators](https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/validators.md#field-validators)を参照してください。

    Args:
        field: `field_validator`が呼び出される最初のフィールドです。これは`fields`とは別のもので、少なくとも1つ渡さないとエラーが発生します。
        *fields: `field_validator`が呼び出される追加フィールドです。
        mode: 検証の前または後にフィールドを検証するかどうかを指定します。
        check_fields: フィールドがモデル上に実際に存在するかどうかをチェックするかどうか。

    Returns:
        field_validatorとして使用する関数を修飾するために使用できるデコレータ。

    Raises:
        PydantictUserError:
            - `@field_validator`が(フィールドなしで)使用されている場合。
            - フィールドとして`@field_validator`に渡された引数が文字列でない場合。
            - `@field_validator`がインスタンスメソッドに適用された場合。
    """
    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", "before", "after"]
) -> Any

Usage Documentation

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]
    '''

詳細な例については、Model Validatorsを参照してください。

Parameters:

Name Type Description Default
mode Literal['wrap', 'before', 'after']

検証モードを指定する必須文字列リテラル。'wrap'、'before'、または'after'のいずれかです。

required

Returns:

Type Description
Any

モデルバリデータとして使用される関数をデコレートするために使用できるデコレータ。

Source code in pydantic/functional_validators.py
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def model_validator(
    *,
    mode: Literal['wrap', 'before', 'after'],
) -> Any:
    """Usage docs: https://yodai-yodai.github.io/translated/pydantic-docs-ja/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]
        '''
    ```

    詳細な例については、[Model Validators](https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/validators.md#model-validators)を参照してください。


    Args:
        mode: 検証モードを指定する必須文字列リテラル。'wrap'、'before'、または'after'のいずれかです。

    Returns:
        モデルバリデータとして使用される関数をデコレートするために使用できるデコレータ。
    """

    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