コンテンツにスキップ

Pydantic Types

pydantic.types

タイプモジュールには、pydanticで使用されるカスタムタイプが含まれています。

StrictBool module-attribute

StrictBool = Annotated[bool, Strict()]

ブール値で、"True"または"False"のいずれかでなければなりません。

PositiveInt module-attribute

PositiveInt = Annotated[int, Gt(0)]

0より大きくなければならない整数。

from pydantic import BaseModel, PositiveInt, ValidationError

class Model(BaseModel):
    positive_int: PositiveInt

m = Model(positive_int=1)
print(repr(m))
#> Model(positive_int=1)

try:
    Model(positive_int=-1)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than',
            'loc': ('positive_int',),
            'msg': 'Input should be greater than 0',
            'input': -1,
            'ctx': {'gt': 0},
            'url': 'https://errors.pydantic.dev/2/v/greater_than',
        }
    ]
    '''

NegativeInt module-attribute

NegativeInt = Annotated[int, Lt(0)]

ゼロより小さくなければならない整数。

from pydantic import BaseModel, NegativeInt, ValidationError

class Model(BaseModel):
    negative_int: NegativeInt

m = Model(negative_int=-1)
print(repr(m))
#> Model(negative_int=-1)

try:
    Model(negative_int=1)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'less_than',
            'loc': ('negative_int',),
            'msg': 'Input should be less than 0',
            'input': 1,
            'ctx': {'lt': 0},
            'url': 'https://errors.pydantic.dev/2/v/less_than',
        }
    ]
    '''

NonPositiveInt module-attribute

NonPositiveInt = Annotated[int, Le(0)]

0以下の整数。

from pydantic import BaseModel, NonPositiveInt, ValidationError

class Model(BaseModel):
    non_positive_int: NonPositiveInt

m = Model(non_positive_int=0)
print(repr(m))
#> Model(non_positive_int=0)

try:
    Model(non_positive_int=1)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'less_than_equal',
            'loc': ('non_positive_int',),
            'msg': 'Input should be less than or equal to 0',
            'input': 1,
            'ctx': {'le': 0},
            'url': 'https://errors.pydantic.dev/2/v/less_than_equal',
        }
    ]
    '''

NonNegativeInt module-attribute

NonNegativeInt = Annotated[int, Ge(0)]

0以上の整数。

from pydantic import BaseModel, NonNegativeInt, ValidationError

class Model(BaseModel):
    non_negative_int: NonNegativeInt

m = Model(non_negative_int=0)
print(repr(m))
#> Model(non_negative_int=0)

try:
    Model(non_negative_int=-1)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than_equal',
            'loc': ('non_negative_int',),
            'msg': 'Input should be greater than or equal to 0',
            'input': -1,
            'ctx': {'ge': 0},
            'url': 'https://errors.pydantic.dev/2/v/greater_than_equal',
        }
    ]
    '''

StrictInt module-attribute

StrictInt = Annotated[int, Strict()]

strictモードで検証する必要がある整数。

from pydantic import BaseModel, StrictInt, ValidationError

class StrictIntModel(BaseModel):
    strict_int: StrictInt

try:
    StrictIntModel(strict_int=3.14159)
except ValidationError as e:
    print(e)
    '''
    1 validation error for StrictIntModel
    strict_int
      Input should be a valid integer [type=int_type, input_value=3.14159, input_type=float]
    '''

PositiveFloat module-attribute

PositiveFloat = Annotated[float, Gt(0)]

0より大きくなければならない浮動小数点。

from pydantic import BaseModel, PositiveFloat, ValidationError

class Model(BaseModel):
    positive_float: PositiveFloat

m = Model(positive_float=1.0)
print(repr(m))
#> Model(positive_float=1.0)

try:
    Model(positive_float=-1.0)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than',
            'loc': ('positive_float',),
            'msg': 'Input should be greater than 0',
            'input': -1.0,
            'ctx': {'gt': 0.0},
            'url': 'https://errors.pydantic.dev/2/v/greater_than',
        }
    ]
    '''

NegativeFloat module-attribute

NegativeFloat = Annotated[float, Lt(0)]

0より小さくなければならない浮動小数点。

from pydantic import BaseModel, NegativeFloat, ValidationError

class Model(BaseModel):
    negative_float: NegativeFloat

m = Model(negative_float=-1.0)
print(repr(m))
#> Model(negative_float=-1.0)

try:
    Model(negative_float=1.0)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'less_than',
            'loc': ('negative_float',),
            'msg': 'Input should be less than 0',
            'input': 1.0,
            'ctx': {'lt': 0.0},
            'url': 'https://errors.pydantic.dev/2/v/less_than',
        }
    ]
    '''

NonPositiveFloat module-attribute

NonPositiveFloat = Annotated[float, Le(0)]

0以下でなければならない浮動小数点。

from pydantic import BaseModel, NonPositiveFloat, ValidationError

class Model(BaseModel):
    non_positive_float: NonPositiveFloat

m = Model(non_positive_float=0.0)
print(repr(m))
#> Model(non_positive_float=0.0)

try:
    Model(non_positive_float=1.0)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'less_than_equal',
            'loc': ('non_positive_float',),
            'msg': 'Input should be less than or equal to 0',
            'input': 1.0,
            'ctx': {'le': 0.0},
            'url': 'https://errors.pydantic.dev/2/v/less_than_equal',
        }
    ]
    '''

NonNegativeFloat module-attribute

NonNegativeFloat = Annotated[float, Ge(0)]

0以上でなければならない浮動小数点。

from pydantic import BaseModel, NonNegativeFloat, ValidationError

class Model(BaseModel):
    non_negative_float: NonNegativeFloat

m = Model(non_negative_float=0.0)
print(repr(m))
#> Model(non_negative_float=0.0)

try:
    Model(non_negative_float=-1.0)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than_equal',
            'loc': ('non_negative_float',),
            'msg': 'Input should be greater than or equal to 0',
            'input': -1.0,
            'ctx': {'ge': 0.0},
            'url': 'https://errors.pydantic.dev/2/v/greater_than_equal',
        }
    ]
    '''

StrictFloat module-attribute

StrictFloat = Annotated[float, Strict(True)]

strictモードで検証する必要があるfloat。

from pydantic import BaseModel, StrictFloat, ValidationError

class StrictFloatModel(BaseModel):
    strict_float: StrictFloat

try:
    StrictFloatModel(strict_float='1.0')
except ValidationError as e:
    print(e)
    '''
    1 validation error for StrictFloatModel
    strict_float
      Input should be a valid number [type=float_type, input_value='1.0', input_type=str]
    '''

FiniteFloat module-attribute

FiniteFloat = Annotated[float, AllowInfNan(False)]

finiteでなければならないfloat("-inf"、"inf"、"nan"ではない)。

from pydantic import BaseModel, FiniteFloat

class Model(BaseModel):
    finite: FiniteFloat

m = Model(finite=1.0)
print(m)
#> finite=1.0

StrictBytes module-attribute

StrictBytes = Annotated[bytes, Strict()]

strictモードで検証する必要があるバイト

StrictStr module-attribute

StrictStr = Annotated[str, Strict()]

strictモードで検証する必要がある文字列

UUID1 module-attribute

UUID1 = Annotated[UUID, UuidVersion(1)]

バージョン1である必要があるUUID

import uuid

from pydantic import UUID1, BaseModel

class Model(BaseModel):
    uuid1: UUID1

Model(uuid1=uuid.uuid1())

UUID3 module-attribute

UUID3 = Annotated[UUID, UuidVersion(3)]

バージョン3である必要があるUUID

import uuid

from pydantic import UUID3, BaseModel

class Model(BaseModel):
    uuid3: UUID3

Model(uuid3=uuid.uuid3(uuid.NAMESPACE_DNS, 'pydantic.org'))

UUID4 module-attribute

UUID4 = Annotated[UUID, UuidVersion(4)]

バージョン4である必要があるUUID

import uuid

from pydantic import UUID4, BaseModel

class Model(BaseModel):
    uuid4: UUID4

Model(uuid4=uuid.uuid4())

UUID5 module-attribute

UUID5 = Annotated[UUID, UuidVersion(5)]

バージョン5である必要があるUUID

import uuid

from pydantic import UUID5, BaseModel

class Model(BaseModel):
    uuid5: UUID5

Model(uuid5=uuid.uuid5(uuid.NAMESPACE_DNS, 'pydantic.org'))

FilePath module-attribute

FilePath = Annotated[Path, PathType('file')]

ファイルへの参照が必要なパス。

from pathlib import Path

from pydantic import BaseModel, FilePath, ValidationError

class Model(BaseModel):
    f: FilePath

path = Path('text.txt')
path.touch()
m = Model(f='text.txt')
print(m.model_dump())
#> {'f': PosixPath('text.txt')}
path.unlink()

path = Path('directory')
path.mkdir(exist_ok=True)
try:
    Model(f='directory')  # directory
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    f
      Path does not point to a file [type=path_not_file, input_value='directory', input_type=str]
    '''
path.rmdir()

try:
    Model(f='not-exists-file')
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    f
      Path does not point to a file [type=path_not_file, input_value='not-exists-file', input_type=str]
    '''

DirectoryPath module-attribute

DirectoryPath = Annotated[Path, PathType('dir')]

ディレクトリへの参照が必要なパス。

from pathlib import Path

from pydantic import BaseModel, DirectoryPath, ValidationError

class Model(BaseModel):
    f: DirectoryPath

path = Path('directory/')
path.mkdir()
m = Model(f='directory/')
print(m.model_dump())
#> {'f': PosixPath('directory')}
path.rmdir()

path = Path('file.txt')
path.touch()
try:
    Model(f='file.txt')  # file
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    f
      Path does not point to a directory [type=path_not_directory, input_value='file.txt', input_type=str]
    '''
path.unlink()

try:
    Model(f='not-exists-directory')
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    f
      Path does not point to a directory [type=path_not_directory, input_value='not-exists-directory', input_type=str]
    '''

NewPath module-attribute

NewPath = Annotated[Path, PathType('new')]

まだ存在していない新しいファイルまたはディレクトリのパス。親ディレクトリはすでに存在している必要があります。

Base64Bytes module-attribute

Base64Bytes = Annotated[
    bytes, EncodedBytes(encoder=Base64Encoder)
]

標準の(URLセーフでない)base64エンコーダを使用してエンコードおよびデコードされるバイトタイプ。

Note

内部的には、Base64Bytesは標準ライブラリbase64.encodebytesbase64.decodebytes関数を使用します。

その結果、Base64Bytesタイプを使用してURLセーフなbase64データをデコードしようとすると、失敗したり、不正なデコードが行われたりする可能性があります。

from pydantic import Base64Bytes, BaseModel, ValidationError

class Model(BaseModel):
    base64_bytes: Base64Bytes

# Initialize the model with base64 data
m = Model(base64_bytes=b'VGhpcyBpcyB0aGUgd2F5')

# Access decoded value
print(m.base64_bytes)
#> b'This is the way'

# Serialize into the base64 form
print(m.model_dump())
#> {'base64_bytes': b'VGhpcyBpcyB0aGUgd2F5
'}

# Validate base64 data
try:
    print(Model(base64_bytes=b'undecodable').base64_bytes)
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    base64_bytes
      Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value=b'undecodable', input_type=bytes]
    '''

Base64Str module-attribute

Base64Str = Annotated[
    str, EncodedStr(encoder=Base64Encoder)
]

標準の(URLセーフでない)base64エンコーダを使用してエンコードおよびデコードされるstrタイプ。

Note

内部的には、Base64Bytesは標準ライブラリbase64.encodebytesbase64.decodebytes関数を使用します。

その結果、Base64Str型を使用してURLセーフなbase64データをデコードしようとすると、失敗したり、不正なデコードが行われたりする可能性があります。

from pydantic import Base64Str, BaseModel, ValidationError

class Model(BaseModel):
    base64_str: Base64Str

# Initialize the model with base64 data
m = Model(base64_str='VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y')

# Access decoded value
print(m.base64_str)
#> These aren't the droids you're looking for

# Serialize into the base64 form
print(m.model_dump())
#> {'base64_str': 'VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y
'}

# Validate base64 data
try:
    print(Model(base64_str='undecodable').base64_str)
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    base64_str
      Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value='undecodable', input_type=str]
    '''

Base64UrlBytes module-attribute

Base64UrlBytes = Annotated[
    bytes, EncodedBytes(encoder=Base64UrlEncoder)
]

URLセーフなbase64エンコーダを使用してエンコードおよびデコードされるバイトタイプ。

Note

内部的には、Base64UrlBytesは標準ライブラリbase64.urlsafe_b64encodeおよびbase64.urlsafe_b64decode関数を使用します。

その結果、Base64UrlBytes型を使用して"普通の"base64データを忠実にデコードすることができます('+''/'を使用)。

from pydantic import Base64UrlBytes, BaseModel

class Model(BaseModel):
    base64url_bytes: Base64UrlBytes

# Initialize the model with base64 data
m = Model(base64url_bytes=b'SHc_dHc-TXc==')
print(m)
#> base64url_bytes=b'Hw?tw>Mw'

Base64UrlStr module-attribute

Base64UrlStr = Annotated[
    str, EncodedStr(encoder=Base64UrlEncoder)
]

URLセーフなbase64エンコーダを使用してエンコードおよびデコードされるstrタイプ。

Note

内部的には、Base64UrlStrは標準ライブラリbase64.urlsafe_b64encodeおよびbase64.urlsafe_b64decode関数を使用します。

その結果、Base64UrlStr型を使用して、"普通の"base64データを忠実にデコードすることができます('+''/'を使用)。

from pydantic import Base64UrlStr, BaseModel

class Model(BaseModel):
    base64url_str: Base64UrlStr

# Initialize the model with base64 data
m = Model(base64url_str='SHc_dHc-TXc==')
print(m)
#> base64url_str='Hw?tw>Mw'

JsonValue module-attribute

JsonValue: TypeAlias = Union[
    List["JsonValue"],
    Dict[str, "JsonValue"],
    str,
    bool,
    int,
    float,
    None,
]

JsonValueは、JSONにシリアライズできる値を表すために使用されます。

次のいずれかになります。

  • List['JsonValue']
  • Dict[str, 'JsonValue']
  • str
  • bool
  • int
  • float
  • None

次の例は、JsonValueを使用してJSONデータを検証する方法と、入力データがJSONシリアライズ可能でない場合に予想されるエラーの種類を示しています。

import json

from pydantic import BaseModel, JsonValue, ValidationError

class Model(BaseModel):
    j: JsonValue

valid_json_data = {'j': {'a': {'b': {'c': 1, 'd': [2, None]}}}}
invalid_json_data = {'j': {'a': {'b': ...}}}

print(repr(Model.model_validate(valid_json_data)))
#> Model(j={'a': {'b': {'c': 1, 'd': [2, None]}}})
print(repr(Model.model_validate_json(json.dumps(valid_json_data))))
#> Model(j={'a': {'b': {'c': 1, 'd': [2, None]}}})

try:
    Model.model_validate(invalid_json_data)
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    j.dict.a.dict.b
      input was not a valid JSON value [type=invalid-json-value, input_value=Ellipsis, input_type=ellipsis]
    '''

OnErrorOmit module-attribute

OnErrorOmit = Annotated[T, _OnErrorOmit]

リスト内の項目として使用される場合、dict内のキータイプ、TypedDictのオプションの値など。 この注釈では、検証中にエラーが発生した場合に、その項目を繰り返し処理から除外します。 つまり、ValidationErrorが伝播されてiterable全体が破棄されるのではなく、無効な項目が破棄されて有効な項目が返されます。

Strict dataclass

Bases: PydanticMetadata, BaseMetadata

フィールドがstrictモードで検証される必要があることを示すフィールドメタデータクラス。

Attributes:

Name Type Description
strict bool

strictモードでフィールドを検証するかどうか。

from typing_extensions import Annotated

from pydantic.types import Strict

StrictBool = Annotated[bool, Strict()]
Source code in pydantic/types.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
@_dataclasses.dataclass
class Strict(_fields.PydanticMetadata, BaseMetadata):
    """Usage docs: https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/strict_mode/#strict-mode-with-annotated-strict

    フィールドがstrictモードで検証される必要があることを示すフィールドメタデータクラス。

    Attributes:
        strict: strictモードでフィールドを検証するかどうか。

    例:
        ```python
        from typing_extensions import Annotated

        from pydantic.types import Strict

        StrictBool = Annotated[bool, Strict()]
        ```
    """

    strict: bool = True

    def __hash__(self) -> int:
        return hash(self.strict)

AllowInfNan dataclass

Bases: PydanticMetadata

フィールドが"-inf"、"inf"、"nan"を許可すべきであることを示すフィールドメタデータクラス。

Source code in pydantic/types.py
379
380
381
382
383
384
385
386
@_dataclasses.dataclass
class AllowInfNan(_fields.PydanticMetadata):
    """フィールドが"-inf"、"inf"、"nan"を許可すべきであることを示すフィールドメタデータクラス。"""

    allow_inf_nan: bool = True

    def __hash__(self) -> int:
        return hash(self.allow_inf_nan)

StringConstraints dataclass

Bases: GroupedMetadata

Usage Documentation

String Constraints

str型に制約を適用します。

Attributes:

Name Type Description
strip_whitespace bool | None

先頭と末尾の空白を削除するかどうか。

to_upper bool | None

文字列を大文字に変換するかどうか。

to_lower bool | None

文字列を小文字に変換するかどうか。

strict bool | None

文字列をstrictモードで検証するかどうか。

min_length int | None

文字列の最小長。

max_length int | None

文字列の最大長。

pattern str | Pattern[str] | None

文字列が一致しなければならない正規表現パターン。

Source code in pydantic/types.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
@_dataclasses.dataclass(frozen=True)
class StringConstraints(annotated_types.GroupedMetadata):
    """Usage docs: https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/fields/#string-constraints

    `str`型に制約を適用します。

    Attributes:
        strip_whitespace: 先頭と末尾の空白を削除するかどうか。
        to_upper: 文字列を大文字に変換するかどうか。
        to_lower: 文字列を小文字に変換するかどうか。
        strict: 文字列をstrictモードで検証するかどうか。
        min_length: 文字列の最小長。
        max_length: 文字列の最大長。
        pattern: 文字列が一致しなければならない正規表現パターン。
    """

    strip_whitespace: bool | None = None
    to_upper: bool | None = None
    to_lower: bool | None = None
    strict: bool | None = None
    min_length: int | None = None
    max_length: int | None = None
    pattern: str | Pattern[str] | None = None

    def __iter__(self) -> Iterator[BaseMetadata]:
        if self.min_length is not None:
            yield MinLen(self.min_length)
        if self.max_length is not None:
            yield MaxLen(self.max_length)
        if self.strict is not None:
            yield Strict(self.strict)
        if (
            self.strip_whitespace is not None
            or self.pattern is not None
            or self.to_lower is not None
            or self.to_upper is not None
        ):
            yield _fields.pydantic_general_metadata(
                strip_whitespace=self.strip_whitespace,
                to_upper=self.to_upper,
                to_lower=self.to_lower,
                pattern=self.pattern,
            )

ImportString

文字列から型をインポートするために使用できる型。

ImportStringは文字列を予期し、そのドットパスでインポート可能なPythonオブジェクトをロードします。 モジュールの属性はモジュールと:または.で区切ることができます。例えば、'math:cos'が与えられた場合、結果のフィールド値は関数cosになります。.が使用され、属性とサブモジュールの両方が同じパスに存在する場合、モジュールが優先されます。

モデルのインスタンス化では、ポインタが評価されてインポートされます。この動作には、次の例に示すような微妙な違いがあります。

適切な動作:

from math import cos

from pydantic import BaseModel, Field, ImportString, ValidationError


class ImportThings(BaseModel):
    obj: ImportString


# A string value will cause an automatic import
my_cos = ImportThings(obj='math.cos')

# You can use the imported function as you would expect
cos_of_0 = my_cos.obj(0)
assert cos_of_0 == 1


# A string whose value cannot be imported will raise an error
try:
    ImportThings(obj='foo.bar')
except ValidationError as e:
    print(e)
    '''
    1 validation error for ImportThings
    obj
    Invalid python path: No module named 'foo.bar' [type=import_error, input_value='foo.bar', input_type=str]
    '''


# Actual python objects can be assigned as well
my_cos = ImportThings(obj=cos)
my_cos_2 = ImportThings(obj='math.cos')
my_cos_3 = ImportThings(obj='math:cos')
assert my_cos == my_cos_2 == my_cos_3


# You can set default field value either as Python object:
class ImportThingsDefaultPyObj(BaseModel):
    obj: ImportString = math.cos


# or as a string value (but only if used with `validate_default=True`)
class ImportThingsDefaultString(BaseModel):
    obj: ImportString = Field(default='math.cos', validate_default=True)


my_cos_default1 = ImportThingsDefaultPyObj()
my_cos_default2 = ImportThingsDefaultString()
assert my_cos_default1.obj == my_cos_default2.obj == math.cos


# note: this will not work!
class ImportThingsMissingValidateDefault(BaseModel):
    obj: ImportString = 'math.cos'

my_cos_default3 = ImportThingsMissingValidateDefault()
assert my_cos_default3.obj == 'math.cos'  # just string, not evaluated

ImportString型をjsonにシリアライズすることも可能です。

from pydantic import BaseModel, ImportString


class ImportThings(BaseModel):
    obj: ImportString


# Create an instance
m = ImportThings(obj='math.cos')
print(m)
#> obj=<built-in function cos>
print(m.model_dump_json())
#> {"obj":"math.cos"}
Source code in pydantic/types.py
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
class ImportString:
    """文字列から型をインポートするために使用できる型。

    `ImportString`は文字列を予期し、そのドットパスでインポート可能なPythonオブジェクトをロードします。
    モジュールの属性はモジュールと`:`または`.`で区切ることができます。例えば、`'math:cos'`が与えられた場合、結果のフィールド値は関数`cos`になります。`.`が使用され、属性とサブモジュールの両方が同じパスに存在する場合、モジュールが優先されます。

    モデルのインスタンス化では、ポインタが評価されてインポートされます。この動作には、次の例に示すような微妙な違いがあります。

    **適切な動作:**
    ```py
    from math import cos

    from pydantic import BaseModel, Field, ImportString, ValidationError


    class ImportThings(BaseModel):
        obj: ImportString


    # A string value will cause an automatic import
    my_cos = ImportThings(obj='math.cos')

    # You can use the imported function as you would expect
    cos_of_0 = my_cos.obj(0)
    assert cos_of_0 == 1


    # A string whose value cannot be imported will raise an error
    try:
        ImportThings(obj='foo.bar')
    except ValidationError as e:
        print(e)
        '''
        1 validation error for ImportThings
        obj
        Invalid python path: No module named 'foo.bar' [type=import_error, input_value='foo.bar', input_type=str]
        '''


    # Actual python objects can be assigned as well
    my_cos = ImportThings(obj=cos)
    my_cos_2 = ImportThings(obj='math.cos')
    my_cos_3 = ImportThings(obj='math:cos')
    assert my_cos == my_cos_2 == my_cos_3


    # You can set default field value either as Python object:
    class ImportThingsDefaultPyObj(BaseModel):
        obj: ImportString = math.cos


    # or as a string value (but only if used with `validate_default=True`)
    class ImportThingsDefaultString(BaseModel):
        obj: ImportString = Field(default='math.cos', validate_default=True)


    my_cos_default1 = ImportThingsDefaultPyObj()
    my_cos_default2 = ImportThingsDefaultString()
    assert my_cos_default1.obj == my_cos_default2.obj == math.cos


    # note: this will not work!
    class ImportThingsMissingValidateDefault(BaseModel):
        obj: ImportString = 'math.cos'

    my_cos_default3 = ImportThingsMissingValidateDefault()
    assert my_cos_default3.obj == 'math.cos'  # just string, not evaluated
    ```

    `ImportString`型をjsonにシリアライズすることも可能です。

    ```py
    from pydantic import BaseModel, ImportString


    class ImportThings(BaseModel):
        obj: ImportString


    # Create an instance
    m = ImportThings(obj='math.cos')
    print(m)
    #> obj=<built-in function cos>
    print(m.model_dump_json())
    #> {"obj":"math.cos"}
    ```
    """

    @classmethod
    def __class_getitem__(cls, item: AnyType) -> AnyType:
        return Annotated[item, cls()]

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source: type[Any], handler: GetCoreSchemaHandler
    ) -> core_schema.CoreSchema:
        serializer = core_schema.plain_serializer_function_ser_schema(cls._serialize, when_used='json')
        if cls is source:
            # Treat bare usage of ImportString (`schema is None`) as the same as ImportString[Any]
            return core_schema.no_info_plain_validator_function(
                function=_validators.import_string, serialization=serializer
            )
        else:
            return core_schema.no_info_before_validator_function(
                function=_validators.import_string, schema=handler(source), serialization=serializer
            )

    @classmethod
    def __get_pydantic_json_schema__(cls, cs: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue:
        return handler(core_schema.str_schema())

    @staticmethod
    def _serialize(v: Any) -> str:
        if isinstance(v, ModuleType):
            return v.__name__
        elif hasattr(v, '__module__') and hasattr(v, '__name__'):
            return f'{v.__module__}.{v.__name__}'
        else:
            return v

    def __repr__(self) -> str:
        return 'ImportString'

UuidVersion dataclass

UUIDバージョンを示すフィールドメタデータクラス。

Source code in pydantic/types.py
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
@_dataclasses.dataclass(**_internal_dataclass.slots_true)
class UuidVersion:
    """[UUID](https://docs.python.org/3/library/uuid.html)バージョンを示すフィールドメタデータクラス。"""

    uuid_version: Literal[1, 3, 4, 5]

    def __get_pydantic_json_schema__(
        self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
    ) -> JsonSchemaValue:
        field_schema = handler(core_schema)
        field_schema.pop('anyOf', None)  # remove the bytes/str union
        field_schema.update(type='string', format=f'uuid{self.uuid_version}')
        return field_schema

    def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
        if isinstance(self, source):
            # used directly as a type
            return core_schema.uuid_schema(version=self.uuid_version)
        else:
            # update existing schema with self.uuid_version
            schema = handler(source)
            _check_annotated_type(schema['type'], 'uuid', self.__class__.__name__)
            schema['version'] = self.uuid_version  # type: ignore
            return schema

    def __hash__(self) -> int:
        return hash(type(self.uuid_version))

Json

解析前にJSONをロードする特殊な型ラッパー。

Jsonデータ型を使用すると、ロードされたデータをパラメータ化された型に検証する前に、Pydanticに生のJSON文字列を最初にロードさせることができます。

from typing import Any, List

from pydantic import BaseModel, Json, ValidationError


class AnyJsonModel(BaseModel):
    json_obj: Json[Any]


class ConstrainedJsonModel(BaseModel):
    json_obj: Json[List[int]]


print(AnyJsonModel(json_obj='{"b": 1}'))
#> json_obj={'b': 1}
print(ConstrainedJsonModel(json_obj='[1, 2, 3]'))
#> json_obj=[1, 2, 3]

try:
    ConstrainedJsonModel(json_obj=12)
except ValidationError as e:
    print(e)
    '''
    1 validation error for ConstrainedJsonModel
    json_obj
    JSON input should be string, bytes or bytearray [type=json_type, input_value=12, input_type=int]
    '''

try:
    ConstrainedJsonModel(json_obj='[a, b]')
except ValidationError as e:
    print(e)
    '''
    1 validation error for ConstrainedJsonModel
    json_obj
    Invalid JSON: expected value at line 1 column 2 [type=json_invalid, input_value='[a, b]', input_type=str]
    '''

try:
    ConstrainedJsonModel(json_obj='["a", "b"]')
except ValidationError as e:
    print(e)
    '''
    2 validation errors for ConstrainedJsonModel
    json_obj.0
    Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
    json_obj.1
    Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='b', input_type=str]
    '''

model_dumpまたはmodel_dump_jsonを使用してモデルをダンプすると、ダンプされた値は元のJSON文字列ではなく検証の結果になります。ただし、引数round_trip=Trueを使用して元のJSON文字列を取得することもできます。

from typing import List

from pydantic import BaseModel, Json


class ConstrainedJsonModel(BaseModel):
    json_obj: Json[List[int]]


print(ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json())
#> {"json_obj":[1,2,3]}
print(
    ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json(round_trip=True)
)
#> {"json_obj":"[1,2,3]"}
Source code in pydantic/types.py
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
class Json:
    """解析前にJSONをロードする特殊な型ラッパー。

    `Json`データ型を使用すると、ロードされたデータをパラメータ化された型に検証する前に、Pydanticに生のJSON文字列を最初にロードさせることができます。

    ```py
    from typing import Any, List

    from pydantic import BaseModel, Json, ValidationError


    class AnyJsonModel(BaseModel):
        json_obj: Json[Any]


    class ConstrainedJsonModel(BaseModel):
        json_obj: Json[List[int]]


    print(AnyJsonModel(json_obj='{"b": 1}'))
    #> json_obj={'b': 1}
    print(ConstrainedJsonModel(json_obj='[1, 2, 3]'))
    #> json_obj=[1, 2, 3]

    try:
        ConstrainedJsonModel(json_obj=12)
    except ValidationError as e:
        print(e)
        '''
        1 validation error for ConstrainedJsonModel
        json_obj
        JSON input should be string, bytes or bytearray [type=json_type, input_value=12, input_type=int]
        '''

    try:
        ConstrainedJsonModel(json_obj='[a, b]')
    except ValidationError as e:
        print(e)
        '''
        1 validation error for ConstrainedJsonModel
        json_obj
        Invalid JSON: expected value at line 1 column 2 [type=json_invalid, input_value='[a, b]', input_type=str]
        '''

    try:
        ConstrainedJsonModel(json_obj='["a", "b"]')
    except ValidationError as e:
        print(e)
        '''
        2 validation errors for ConstrainedJsonModel
        json_obj.0
        Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
        json_obj.1
        Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='b', input_type=str]
        '''
    ```

    `model_dump`または`model_dump_json`を使用してモデルをダンプすると、ダンプされた値は元のJSON文字列ではなく検証の結果になります。ただし、引数`round_trip=True`を使用して元のJSON文字列を取得することもできます。

    ```py
    from typing import List

    from pydantic import BaseModel, Json


    class ConstrainedJsonModel(BaseModel):
        json_obj: Json[List[int]]


    print(ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json())
    #> {"json_obj":[1,2,3]}
    print(
        ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json(round_trip=True)
    )
    #> {"json_obj":"[1,2,3]"}
    ```
    """

    @classmethod
    def __class_getitem__(cls, item: AnyType) -> AnyType:
        return Annotated[item, cls()]

    @classmethod
    def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
        if cls is source:
            return core_schema.json_schema(None)
        else:
            return core_schema.json_schema(handler(source))

    def __repr__(self) -> str:
        return 'Json'

    def __hash__(self) -> int:
        return hash(type(self))

    def __eq__(self, other: Any) -> bool:
        return type(other) == type(self)

Secret

Bases: _SecretBase[SecretType]

ロギングやトレースバックで表示したくない機密情報を含むフィールドを定義するために使用される汎用基本クラス。

Secretを型で直接パラメータ化するか、またはSecretのサブクラスをパラメータ化された型でパラメータ化することができます。サブクラス化の利点は、repr()およびstr()メソッドに使用されるカスタム_displayメソッドを定義できることです。以下の例は、Secretを使用して新しいシークレット型を作成する両方の方法を示しています。

  1. Secret型を直接パラメータ化する:
from pydantic import BaseModel, Secret

SecretBool = Secret[bool]

class Model(BaseModel):
    secret_bool: SecretBool

m = Model(secret_bool=True)
print(m.model_dump())
#> {'secret_bool': Secret('**********')}

print(m.model_dump_json())
#> {"secret_bool":"**********"}

print(m.secret_bool.get_secret_value())
#> True
  1. パラメータ化されたSecretからのサブクラス化:
from datetime import date

from pydantic import BaseModel, Secret

class SecretDate(Secret[date]):
    def _display(self) -> str:
        return '****/**/**'

class Model(BaseModel):
    secret_date: SecretDate

m = Model(secret_date=date(2022, 1, 1))
print(m.model_dump())
#> {'secret_date': SecretDate('****/**/**')}

print(m.model_dump_json())
#> {"secret_date":"****/**/**"}

print(m.secret_date.get_secret_value())
#> 2022-01-01

_displayメソッドが返す値はrepr()str()に使用されます。

Source code in pydantic/types.py
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
class Secret(_SecretBase[SecretType]):
    """ロギングやトレースバックで表示したくない機密情報を含むフィールドを定義するために使用される汎用基本クラス。

    `Secret`を型で直接パラメータ化するか、または`Secret`のサブクラスをパラメータ化された型でパラメータ化することができます。サブクラス化の利点は、`repr()`および`str()`メソッドに使用されるカスタム`_display`メソッドを定義できることです。以下の例は、`Secret`を使用して新しいシークレット型を作成する両方の方法を示しています。

    1. `Secret`型を直接パラメータ化する:

    ```py
    from pydantic import BaseModel, Secret

    SecretBool = Secret[bool]

    class Model(BaseModel):
        secret_bool: SecretBool

    m = Model(secret_bool=True)
    print(m.model_dump())
    #> {'secret_bool': Secret('**********')}

    print(m.model_dump_json())
    #> {"secret_bool":"**********"}

    print(m.secret_bool.get_secret_value())
    #> True
    ```

    2. パラメータ化された`Secret`からのサブクラス化:

    ```py
    from datetime import date

    from pydantic import BaseModel, Secret

    class SecretDate(Secret[date]):
        def _display(self) -> str:
            return '****/**/**'

    class Model(BaseModel):
        secret_date: SecretDate

    m = Model(secret_date=date(2022, 1, 1))
    print(m.model_dump())
    #> {'secret_date': SecretDate('****/**/**')}

    print(m.model_dump_json())
    #> {"secret_date":"****/**/**"}

    print(m.secret_date.get_secret_value())
    #> 2022-01-01
    ```

    `_display`メソッドが返す値は`repr()`と`str()`に使用されます。
    """

    def _display(self) -> str | bytes:
        return '**********' if self.get_secret_value() else ''

    @classmethod
    def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
        inner_type = None
        # if origin_type is Secret, then cls is a GenericAlias, and we can extract the inner type directly
        origin_type = get_origin(source)
        if origin_type is not None:
            inner_type = get_args(source)[0]
        # otherwise, we need to get the inner type from the base class
        else:
            bases = getattr(cls, '__orig_bases__', getattr(cls, '__bases__', []))
            for base in bases:
                if get_origin(base) is Secret:
                    inner_type = get_args(base)[0]
            if bases == [] or inner_type is None:
                raise TypeError(
                    f"Can't get secret type from {cls.__name__}. "
                    'Please use Secret[<type>], or subclass from Secret[<type>] instead.'
                )

        inner_schema = handler.generate_schema(inner_type)  # type: ignore

        def validate_secret_value(value, handler) -> Secret[SecretType]:
            if isinstance(value, Secret):
                value = value.get_secret_value()
            validated_inner = handler(value)
            return cls(validated_inner)

        def serialize(value: Secret[SecretType], info: core_schema.SerializationInfo) -> str | Secret[SecretType]:
            if info.mode == 'json':
                return str(value)
            else:
                return value

        return core_schema.json_or_python_schema(
            python_schema=core_schema.no_info_wrap_validator_function(
                validate_secret_value,
                inner_schema,
            ),
            json_schema=core_schema.no_info_after_validator_function(lambda x: cls(x), inner_schema),
            serialization=core_schema.plain_serializer_function_ser_schema(
                serialize,
                info_arg=True,
                when_used='always',
            ),
        )

SecretStr

Bases: _SecretField[str]

ロギングやトレースバックで表示したくない機密情報を格納するために使用される文字列。

シークレットの値が空でない場合、repr()str()の呼び出しでは、元になる値の代わりに'**********'として表示されます。 value_is_emptyの場合は、""と表示されます。

from pydantic import BaseModel, SecretStr

class User(BaseModel):
    username: str
    password: SecretStr

user = User(username='scolvin', password='password1')

print(user)
#> username='scolvin' password=SecretStr('**********')
print(user.password.get_secret_value())
#> password1
print((SecretStr('password'), SecretStr('')))
#> (SecretStr('**********'), SecretStr(''))
Source code in pydantic/types.py
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
class SecretStr(_SecretField[str]):
    """ロギングやトレースバックで表示したくない機密情報を格納するために使用される文字列。

    シークレットの値が空でない場合、`repr()`や`str()`の呼び出しでは、元になる値の代わりに`'**********'`として表示されます。
    value_is_emptyの場合は、""と表示されます。

    ```py
    from pydantic import BaseModel, SecretStr

    class User(BaseModel):
        username: str
        password: SecretStr

    user = User(username='scolvin', password='password1')

    print(user)
    #> username='scolvin' password=SecretStr('**********')
    print(user.password.get_secret_value())
    #> password1
    print((SecretStr('password'), SecretStr('')))
    #> (SecretStr('**********'), SecretStr(''))
    ```
    """

    _inner_schema: ClassVar[CoreSchema] = core_schema.str_schema()
    _error_kind: ClassVar[str] = 'string_type'

    def __len__(self) -> int:
        return len(self._secret_value)

    def _display(self) -> str:
        return _secret_display(self._secret_value)

SecretBytes

Bases: _SecretField[bytes]

ログやトレースバックに表示したくない機密情報を保存するために使用されるバイト。

repr()str()を呼び出すと、文字列値の代わりにb'**********'が表示されます。 シークレット値が空でない場合、repr()str()の呼び出しでは、元になる値の代わりにb'**********'として表示されます。

from pydantic import BaseModel, SecretBytes

class User(BaseModel):
    username: str
    password: SecretBytes

user = User(username='scolvin', password=b'password1')
#> username='scolvin' password=SecretBytes(b'**********')
print(user.password.get_secret_value())
#> b'password1'
print((SecretBytes(b'password'), SecretBytes(b'')))
#> (SecretBytes(b'**********'), SecretBytes(b''))
Source code in pydantic/types.py
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
class SecretBytes(_SecretField[bytes]):
    """ログやトレースバックに表示したくない機密情報を保存するために使用されるバイト。

    `repr()`や`str()`を呼び出すと、文字列値の代わりに`b'**********'`が表示されます。
    シークレット値が空でない場合、`repr()`や`str()`の呼び出しでは、元になる値の代わりに`b'**********'`として表示されます。

    ```py
    from pydantic import BaseModel, SecretBytes

    class User(BaseModel):
        username: str
        password: SecretBytes

    user = User(username='scolvin', password=b'password1')
    #> username='scolvin' password=SecretBytes(b'**********')
    print(user.password.get_secret_value())
    #> b'password1'
    print((SecretBytes(b'password'), SecretBytes(b'')))
    #> (SecretBytes(b'**********'), SecretBytes(b''))
    ```
    """

    _inner_schema: ClassVar[CoreSchema] = core_schema.bytes_schema()
    _error_kind: ClassVar[str] = 'bytes_type'

    def __len__(self) -> int:
        return len(self._secret_value)

    def _display(self) -> bytes:
        return _secret_display(self._secret_value).encode()

PaymentCardNumber

Bases: str

https://en.wikipedia.org/wiki/Payment_card_numberに基づきます。

Source code in pydantic/types.py
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
@deprecated(
    'The `PaymentCardNumber` class is deprecated, use `pydantic_extra_types` instead. '
    'See https://docs.pydantic.dev/latest/api/pydantic_extra_types_payment/#pydantic_extra_types.payment.PaymentCardNumber.',
    category=PydanticDeprecatedSince20,
)
class PaymentCardNumber(str):
    """https://en.wikipedia.org/wiki/Payment_card_numberに基づきます。"""

    strip_whitespace: ClassVar[bool] = True
    min_length: ClassVar[int] = 12
    max_length: ClassVar[int] = 19
    bin: str
    last4: str
    brand: PaymentCardBrand

    def __init__(self, card_number: str):
        self.validate_digits(card_number)

        card_number = self.validate_luhn_check_digit(card_number)

        self.bin = card_number[:6]
        self.last4 = card_number[-4:]
        self.brand = self.validate_brand(card_number)

    @classmethod
    def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
        return core_schema.with_info_after_validator_function(
            cls.validate,
            core_schema.str_schema(
                min_length=cls.min_length, max_length=cls.max_length, strip_whitespace=cls.strip_whitespace
            ),
        )

    @classmethod
    def validate(cls, input_value: str, /, _: core_schema.ValidationInfo) -> PaymentCardNumber:
        """カード番号を検証して、`PaymentCardNumber`インスタンスを返します。"""
        return cls(input_value)

    @property
    def masked(self) -> str:
        """カード番号の最後の4桁を除くすべてをマスクします。

        Returns:
            マスクされたカード番号文字列。
        """
        num_masked = len(self) - 10  # len(bin) + len(last4) == 10
        return f'{self.bin}{"*" * num_masked}{self.last4}'

    @classmethod
    def validate_digits(cls, card_number: str) -> None:
        """カード番号がすべて数字であることを確認します。"""
        if not card_number.isdigit():
            raise PydanticCustomError('payment_card_number_digits', 'Card number is not all digits')

    @classmethod
    def validate_luhn_check_digit(cls, card_number: str) -> str:
        """https://en.wikipedia.org/wiki/Luhn_algorithmに基づきます。"""
        sum_ = int(card_number[-1])
        length = len(card_number)
        parity = length % 2
        for i in range(length - 1):
            digit = int(card_number[i])
            if i % 2 == parity:
                digit *= 2
            if digit > 9:
                digit -= 9
            sum_ += digit
        valid = sum_ % 10 == 0
        if not valid:
            raise PydanticCustomError('payment_card_number_luhn', 'Card number is not luhn valid')
        return card_number

    @staticmethod
    def validate_brand(card_number: str) -> PaymentCardBrand:
        """主要ブランドのBINに基づいて長さを検証します:
        https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN)
        """
        if card_number[0] == '4':
            brand = PaymentCardBrand.visa
        elif 51 <= int(card_number[:2]) <= 55:
            brand = PaymentCardBrand.mastercard
        elif card_number[:2] in {'34', '37'}:
            brand = PaymentCardBrand.amex
        else:
            brand = PaymentCardBrand.other

        required_length: None | int | str = None
        if brand in PaymentCardBrand.mastercard:
            required_length = 16
            valid = len(card_number) == required_length
        elif brand == PaymentCardBrand.visa:
            required_length = '13, 16 or 19'
            valid = len(card_number) in {13, 16, 19}
        elif brand == PaymentCardBrand.amex:
            required_length = 15
            valid = len(card_number) == required_length
        else:
            valid = True

        if not valid:
            raise PydanticCustomError(
                'payment_card_number_brand',
                'Length for a {brand} card must be {required_length}',
                {'brand': brand, 'required_length': required_length},
            )
        return brand

masked property

masked: str

カード番号の最後の4桁を除くすべてをマスクします。

Returns:

Type Description
str

マスクされたカード番号文字列。

validate classmethod

validate(
    input_value: str, /, _: ValidationInfo
) -> PaymentCardNumber

カード番号を検証して、PaymentCardNumberインスタンスを返します。

Source code in pydantic/types.py
1738
1739
1740
1741
@classmethod
def validate(cls, input_value: str, /, _: core_schema.ValidationInfo) -> PaymentCardNumber:
    """カード番号を検証して、`PaymentCardNumber`インスタンスを返します。"""
    return cls(input_value)

validate_digits classmethod

validate_digits(card_number: str) -> None

カード番号がすべて数字であることを確認します。

Source code in pydantic/types.py
1753
1754
1755
1756
1757
@classmethod
def validate_digits(cls, card_number: str) -> None:
    """カード番号がすべて数字であることを確認します。"""
    if not card_number.isdigit():
        raise PydanticCustomError('payment_card_number_digits', 'Card number is not all digits')

validate_luhn_check_digit classmethod

validate_luhn_check_digit(card_number: str) -> str

https://en.wikipedia.org/wiki/Luhn_algorithmに基づきます。

Source code in pydantic/types.py
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
@classmethod
def validate_luhn_check_digit(cls, card_number: str) -> str:
    """https://en.wikipedia.org/wiki/Luhn_algorithmに基づきます。"""
    sum_ = int(card_number[-1])
    length = len(card_number)
    parity = length % 2
    for i in range(length - 1):
        digit = int(card_number[i])
        if i % 2 == parity:
            digit *= 2
        if digit > 9:
            digit -= 9
        sum_ += digit
    valid = sum_ % 10 == 0
    if not valid:
        raise PydanticCustomError('payment_card_number_luhn', 'Card number is not luhn valid')
    return card_number

validate_brand staticmethod

validate_brand(card_number: str) -> PaymentCardBrand

主要ブランドのBINに基づいて長さを検証します: https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN)

Source code in pydantic/types.py
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
@staticmethod
def validate_brand(card_number: str) -> PaymentCardBrand:
    """主要ブランドのBINに基づいて長さを検証します:
    https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN)
    """
    if card_number[0] == '4':
        brand = PaymentCardBrand.visa
    elif 51 <= int(card_number[:2]) <= 55:
        brand = PaymentCardBrand.mastercard
    elif card_number[:2] in {'34', '37'}:
        brand = PaymentCardBrand.amex
    else:
        brand = PaymentCardBrand.other

    required_length: None | int | str = None
    if brand in PaymentCardBrand.mastercard:
        required_length = 16
        valid = len(card_number) == required_length
    elif brand == PaymentCardBrand.visa:
        required_length = '13, 16 or 19'
        valid = len(card_number) in {13, 16, 19}
    elif brand == PaymentCardBrand.amex:
        required_length = 15
        valid = len(card_number) == required_length
    else:
        valid = True

    if not valid:
        raise PydanticCustomError(
            'payment_card_number_brand',
            'Length for a {brand} card must be {required_length}',
            {'brand': brand, 'required_length': required_length},
        )
    return brand

ByteSize

Bases: int

単位付きのバイト数を表す文字列("1 KB"や"11.5 MiB"など)を整数に変換します。

ByteSizeデータ型を使用すると、バイト数の文字列表現を(大文字小文字を区別せずに)整数に変換したり、バイト数を表す人間が読める文字列を出力したりできます。

IEC 80000-13 Standardに準拠して、"1 KB"は1000バイトを意味し、"1 KiB"は1024バイトを意味すると解釈されます。一般に、中間の"i"を含めると、単位は10の累乗ではなく2の累乗として解釈されます(たとえば、"1 MB"は"1_000_000"バイトとして扱われ、"1 MiB"は"1_048_576"バイトとして扱われます)。

Info

1bは"1 bit"ではなく"1 byte"として解析されることに注意してください。

from pydantic import BaseModel, ByteSize

class MyModel(BaseModel):
    size: ByteSize

print(MyModel(size=52000).size)
#> 52000
print(MyModel(size='3000 KiB').size)
#> 3072000

m = MyModel(size='50 PB')
print(m.size.human_readable())
#> 44.4PiB
print(m.size.human_readable(decimal=True))
#> 50.0PB
print(m.size.human_readable(separator=' '))
#> 44.4 PiB

print(m.size.to('TiB'))
#> 45474.73508864641
Source code in pydantic/types.py
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
class ByteSize(int):
    """単位付きのバイト数を表す文字列("1 KB"や"11.5 MiB"など)を整数に変換します。

    `ByteSize`データ型を使用すると、バイト数の文字列表現を(大文字小文字を区別せずに)整数に変換したり、バイト数を表す人間が読める文字列を出力したりできます。

    [IEC 80000-13 Standard](https://en.wikipedia.org/wiki/ISO/IEC_80000)に準拠して、"1 KB"は1000バイトを意味し、"1 KiB"は1024バイトを意味すると解釈されます。一般に、中間の"i"を含めると、単位は10の累乗ではなく2の累乗として解釈されます(たとえば、"1 MB"は"1_000_000"バイトとして扱われ、"1 MiB"は"1_048_576"バイトとして扱われます)。

    !!! info
        `1b`は"1 bit"ではなく"1 byte"として解析されることに注意してください。

    ```py
    from pydantic import BaseModel, ByteSize

    class MyModel(BaseModel):
        size: ByteSize

    print(MyModel(size=52000).size)
    #> 52000
    print(MyModel(size='3000 KiB').size)
    #> 3072000

    m = MyModel(size='50 PB')
    print(m.size.human_readable())
    #> 44.4PiB
    print(m.size.human_readable(decimal=True))
    #> 50.0PB
    print(m.size.human_readable(separator=' '))
    #> 44.4 PiB

    print(m.size.to('TiB'))
    #> 45474.73508864641
    ```
    """

    byte_sizes = {
        'b': 1,
        'kb': 10**3,
        'mb': 10**6,
        'gb': 10**9,
        'tb': 10**12,
        'pb': 10**15,
        'eb': 10**18,
        'kib': 2**10,
        'mib': 2**20,
        'gib': 2**30,
        'tib': 2**40,
        'pib': 2**50,
        'eib': 2**60,
        'bit': 1 / 8,
        'kbit': 10**3 / 8,
        'mbit': 10**6 / 8,
        'gbit': 10**9 / 8,
        'tbit': 10**12 / 8,
        'pbit': 10**15 / 8,
        'ebit': 10**18 / 8,
        'kibit': 2**10 / 8,
        'mibit': 2**20 / 8,
        'gibit': 2**30 / 8,
        'tibit': 2**40 / 8,
        'pibit': 2**50 / 8,
        'eibit': 2**60 / 8,
    }
    byte_sizes.update({k.lower()[0]: v for k, v in byte_sizes.items() if 'i' not in k})

    byte_string_pattern = r'^\s*(\d*\.?\d+)\s*(\w+)?'
    byte_string_re = re.compile(byte_string_pattern, re.IGNORECASE)

    @classmethod
    def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
        return core_schema.with_info_after_validator_function(
            function=cls._validate,
            schema=core_schema.union_schema(
                [
                    core_schema.str_schema(pattern=cls.byte_string_pattern),
                    core_schema.int_schema(ge=0),
                ],
                custom_error_type='byte_size',
                custom_error_message='could not parse value and unit from byte string',
            ),
            serialization=core_schema.plain_serializer_function_ser_schema(
                int, return_schema=core_schema.int_schema(ge=0)
            ),
        )

    @classmethod
    def _validate(cls, input_value: Any, /, _: core_schema.ValidationInfo) -> ByteSize:
        try:
            return cls(int(input_value))
        except ValueError:
            pass

        str_match = cls.byte_string_re.match(str(input_value))
        if str_match is None:
            raise PydanticCustomError('byte_size', 'could not parse value and unit from byte string')

        scalar, unit = str_match.groups()
        if unit is None:
            unit = 'b'

        try:
            unit_mult = cls.byte_sizes[unit.lower()]
        except KeyError:
            raise PydanticCustomError('byte_size_unit', 'could not interpret byte unit: {unit}', {'unit': unit})

        return cls(int(float(scalar) * unit_mult))

    def human_readable(self, decimal: bool = False, separator: str = '') -> str:
        """バイトサイズを人間が読める文字列に変換します。

        Args:
            decimal: Trueの場合、10進単位(例:KBあたり1000バイト)を使用します。Falseの場合、バイナリ単位(例:KiBあたり1024バイト)を使用します。
            separator: 値と単位の分割に使用される文字列。デフォルトは空の文字列('')です。

        Returns:
            人間が判読可能なバイト・サイズの文字列表現。
        """
        if decimal:
            divisor = 1000
            units = 'B', 'KB', 'MB', 'GB', 'TB', 'PB'
            final_unit = 'EB'
        else:
            divisor = 1024
            units = 'B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'
            final_unit = 'EiB'

        num = float(self)
        for unit in units:
            if abs(num) < divisor:
                if unit == 'B':
                    return f'{num:0.0f}{separator}{unit}'
                else:
                    return f'{num:0.1f}{separator}{unit}'
            num /= divisor

        return f'{num:0.1f}{separator}{final_unit}'

    def to(self, unit: str) -> float:
        """バイトサイズを、バイト単位とビット単位の両方を含む別の単位に変換します。

        Args:
            unit: 変換先の単位。次のいずれかである必要があります。
                B, KB, MB, GB, TB, PB, EB,
                KiB, MiB, GiB, TiB, PiB, EiB (byte units)
                bit, kbit, mbit, gbit, tbit, pbit, ebit,
                kibit, mibit, gibit, tibit, pibit, eibit (bit units).

        Returns:
            新しい単位のバイトサイズ。
        """
        try:
            unit_div = self.byte_sizes[unit.lower()]
        except KeyError:
            raise PydanticCustomError('byte_size_unit', 'Could not interpret byte unit: {unit}', {'unit': unit})

        return self / unit_div

human_readable

human_readable(
    decimal: bool = False, separator: str = ""
) -> str

バイトサイズを人間が読める文字列に変換します。

Parameters:

Name Type Description Default
decimal bool

Trueの場合、10進単位(例:KBあたり1000バイト)を使用します。Falseの場合、バイナリ単位(例:KiBあたり1024バイト)を使用します。

False
separator str

値と単位の分割に使用される文字列。デフォルトは空の文字列('')です。

''

Returns:

Type Description
str

人間が判読可能なバイト・サイズの文字列表現。

Source code in pydantic/types.py
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
def human_readable(self, decimal: bool = False, separator: str = '') -> str:
    """バイトサイズを人間が読める文字列に変換します。

    Args:
        decimal: Trueの場合、10進単位(例:KBあたり1000バイト)を使用します。Falseの場合、バイナリ単位(例:KiBあたり1024バイト)を使用します。
        separator: 値と単位の分割に使用される文字列。デフォルトは空の文字列('')です。

    Returns:
        人間が判読可能なバイト・サイズの文字列表現。
    """
    if decimal:
        divisor = 1000
        units = 'B', 'KB', 'MB', 'GB', 'TB', 'PB'
        final_unit = 'EB'
    else:
        divisor = 1024
        units = 'B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'
        final_unit = 'EiB'

    num = float(self)
    for unit in units:
        if abs(num) < divisor:
            if unit == 'B':
                return f'{num:0.0f}{separator}{unit}'
            else:
                return f'{num:0.1f}{separator}{unit}'
        num /= divisor

    return f'{num:0.1f}{separator}{final_unit}'

to

to(unit: str) -> float

バイトサイズを、バイト単位とビット単位の両方を含む別の単位に変換します。

Parameters:

Name Type Description Default
unit str

変換先の単位。次のいずれかである必要があります。 B, KB, MB, GB, TB, PB, EB, KiB, MiB, GiB, TiB, PiB, EiB (byte units) bit, kbit, mbit, gbit, tbit, pbit, ebit, kibit, mibit, gibit, tibit, pibit, eibit (bit units).

required

Returns:

Type Description
float

新しい単位のバイトサイズ。

Source code in pydantic/types.py
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
def to(self, unit: str) -> float:
    """バイトサイズを、バイト単位とビット単位の両方を含む別の単位に変換します。

    Args:
        unit: 変換先の単位。次のいずれかである必要があります。
            B, KB, MB, GB, TB, PB, EB,
            KiB, MiB, GiB, TiB, PiB, EiB (byte units)
            bit, kbit, mbit, gbit, tbit, pbit, ebit,
            kibit, mibit, gibit, tibit, pibit, eibit (bit units).

    Returns:
        新しい単位のバイトサイズ。
    """
    try:
        unit_div = self.byte_sizes[unit.lower()]
    except KeyError:
        raise PydanticCustomError('byte_size_unit', 'Could not interpret byte unit: {unit}', {'unit': unit})

    return self / unit_div

PastDate

過去の日付

Source code in pydantic/types.py
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
class PastDate:
    """過去の日付"""

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source: type[Any], handler: GetCoreSchemaHandler
    ) -> core_schema.CoreSchema:
        if cls is source:
            # used directly as a type
            return core_schema.date_schema(now_op='past')
        else:
            schema = handler(source)
            _check_annotated_type(schema['type'], 'date', cls.__name__)
            schema['now_op'] = 'past'
            return schema

    def __repr__(self) -> str:
        return 'PastDate'

FutureDate

未来の日付

Source code in pydantic/types.py
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
class FutureDate:
    """未来の日付"""

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source: type[Any], handler: GetCoreSchemaHandler
    ) -> core_schema.CoreSchema:
        if cls is source:
            # used directly as a type
            return core_schema.date_schema(now_op='future')
        else:
            schema = handler(source)
            _check_annotated_type(schema['type'], 'date', cls.__name__)
            schema['now_op'] = 'future'
            return schema

    def __repr__(self) -> str:
        return 'FutureDate'

AwareDatetime

タイムゾーン情報を必要とする日時。

Source code in pydantic/types.py
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
class AwareDatetime:
    """タイムゾーン情報を必要とする日時。"""

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source: type[Any], handler: GetCoreSchemaHandler
    ) -> core_schema.CoreSchema:
        if cls is source:
            # used directly as a type
            return core_schema.datetime_schema(tz_constraint='aware')
        else:
            schema = handler(source)
            _check_annotated_type(schema['type'], 'datetime', cls.__name__)
            schema['tz_constraint'] = 'aware'
            return schema

    def __repr__(self) -> str:
        return 'AwareDatetime'

NaiveDatetime

タイムゾーン情報を必要としない日時。

Source code in pydantic/types.py
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
class NaiveDatetime:
    """タイムゾーン情報を必要としない日時。"""

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source: type[Any], handler: GetCoreSchemaHandler
    ) -> core_schema.CoreSchema:
        if cls is source:
            # used directly as a type
            return core_schema.datetime_schema(tz_constraint='naive')
        else:
            schema = handler(source)
            _check_annotated_type(schema['type'], 'datetime', cls.__name__)
            schema['tz_constraint'] = 'naive'
            return schema

    def __repr__(self) -> str:
        return 'NaiveDatetime'

PastDatetime

過去の日時。

Source code in pydantic/types.py
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
class PastDatetime:
    """過去の日時。"""

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source: type[Any], handler: GetCoreSchemaHandler
    ) -> core_schema.CoreSchema:
        if cls is source:
            # used directly as a type
            return core_schema.datetime_schema(now_op='past')
        else:
            schema = handler(source)
            _check_annotated_type(schema['type'], 'datetime', cls.__name__)
            schema['now_op'] = 'past'
            return schema

    def __repr__(self) -> str:
        return 'PastDatetime'

FutureDatetime

未来の日時

Source code in pydantic/types.py
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
class FutureDatetime:
    """未来の日時"""

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source: type[Any], handler: GetCoreSchemaHandler
    ) -> core_schema.CoreSchema:
        if cls is source:
            # used directly as a type
            return core_schema.datetime_schema(now_op='future')
        else:
            schema = handler(source)
            _check_annotated_type(schema['type'], 'datetime', cls.__name__)
            schema['now_op'] = 'future'
            return schema

    def __repr__(self) -> str:
        return 'FutureDatetime'

EncoderProtocol

Bases: Protocol

バイトとの間でデータをエンコードおよびデコードするためのプロトコル。

Source code in pydantic/types.py
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
class EncoderProtocol(Protocol):
    """バイトとの間でデータをエンコードおよびデコードするためのプロトコル。"""

    @classmethod
    def decode(cls, data: bytes) -> bytes:
        """エンコーダを使用してデータをデコードします。

        Args:
            data: デコードするデータ。

        Returns:
            デコードされたデータ。
        """
        ...

    @classmethod
    def encode(cls, value: bytes) -> bytes:
        """エンコーダを使用してデータをエンコードします。

        Args:
            value: エンコードするデータ。

        Returns:
            エンコードされたデータ。
        """
        ...

    @classmethod
    def get_json_format(cls) -> str:
        """エンコードされたデータのJSONフォーマットを取得します。

        Returns:
            エンコードされたデータのJSONフォーマット。
        """
        ...

decode classmethod

decode(data: bytes) -> bytes

エンコーダを使用してデータをデコードします。

Parameters:

Name Type Description Default
data bytes

デコードするデータ。

required

Returns:

Type Description
bytes

デコードされたデータ。

Source code in pydantic/types.py
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
@classmethod
def decode(cls, data: bytes) -> bytes:
    """エンコーダを使用してデータをデコードします。

    Args:
        data: デコードするデータ。

    Returns:
        デコードされたデータ。
    """
    ...

encode classmethod

encode(value: bytes) -> bytes

エンコーダを使用してデータをエンコードします。

Parameters:

Name Type Description Default
value bytes

エンコードするデータ。

required

Returns:

Type Description
bytes

エンコードされたデータ。

Source code in pydantic/types.py
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
@classmethod
def encode(cls, value: bytes) -> bytes:
    """エンコーダを使用してデータをエンコードします。

    Args:
        value: エンコードするデータ。

    Returns:
        エンコードされたデータ。
    """
    ...

get_json_format classmethod

get_json_format() -> str

エンコードされたデータのJSONフォーマットを取得します。

Returns:

Type Description
str

エンコードされたデータのJSONフォーマット。

Source code in pydantic/types.py
2169
2170
2171
2172
2173
2174
2175
2176
@classmethod
def get_json_format(cls) -> str:
    """エンコードされたデータのJSONフォーマットを取得します。

    Returns:
        エンコードされたデータのJSONフォーマット。
    """
    ...

Base64Encoder

Bases: EncoderProtocol

標準(URLセーフではない)Base64エンコーダ。

Source code in pydantic/types.py
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
class Base64Encoder(EncoderProtocol):
    """標準(URLセーフではない)Base64エンコーダ。"""

    @classmethod
    def decode(cls, data: bytes) -> bytes:
        """base64でエンコードされたバイトから元のバイトデータにデータをデコードします。

        Args:
            data: デコードするデータ。

        Returns:
            デコードされたデータ。
        """
        try:
            return base64.decodebytes(data)
        except ValueError as e:
            raise PydanticCustomError('base64_decode', "Base64 decoding error: '{error}'", {'error': str(e)})

    @classmethod
    def encode(cls, value: bytes) -> bytes:
        """データをバイトからbase64エンコードされたバイトにエンコードします。

        Args:
            value: エンコードするデータ。

        Returns:
            エンコードされたデータ。
        """
        return base64.encodebytes(value)

    @classmethod
    def get_json_format(cls) -> Literal['base64']:
        """エンコードされたデータのJSONフォーマットを取得します。

        Returns:
            エンコードされたデータのJSONフォーマット。
        """
        return 'base64'

decode classmethod

decode(data: bytes) -> bytes

base64でエンコードされたバイトから元のバイトデータにデータをデコードします。

Parameters:

Name Type Description Default
data bytes

デコードするデータ。

required

Returns:

Type Description
bytes

デコードされたデータ。

Source code in pydantic/types.py
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
@classmethod
def decode(cls, data: bytes) -> bytes:
    """base64でエンコードされたバイトから元のバイトデータにデータをデコードします。

    Args:
        data: デコードするデータ。

    Returns:
        デコードされたデータ。
    """
    try:
        return base64.decodebytes(data)
    except ValueError as e:
        raise PydanticCustomError('base64_decode', "Base64 decoding error: '{error}'", {'error': str(e)})

encode classmethod

encode(value: bytes) -> bytes

データをバイトからbase64エンコードされたバイトにエンコードします。

Parameters:

Name Type Description Default
value bytes

エンコードするデータ。

required

Returns:

Type Description
bytes

エンコードされたデータ。

Source code in pydantic/types.py
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
@classmethod
def encode(cls, value: bytes) -> bytes:
    """データをバイトからbase64エンコードされたバイトにエンコードします。

    Args:
        value: エンコードするデータ。

    Returns:
        エンコードされたデータ。
    """
    return base64.encodebytes(value)

get_json_format classmethod

get_json_format() -> Literal['base64']

エンコードされたデータのJSONフォーマットを取得します。

Returns:

Type Description
Literal['base64']

エンコードされたデータのJSONフォーマット。

Source code in pydantic/types.py
2209
2210
2211
2212
2213
2214
2215
2216
@classmethod
def get_json_format(cls) -> Literal['base64']:
    """エンコードされたデータのJSONフォーマットを取得します。

    Returns:
        エンコードされたデータのJSONフォーマット。
    """
    return 'base64'

Base64UrlEncoder

Bases: EncoderProtocol

URLセーフなBase64エンコーダ。

Source code in pydantic/types.py
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
class Base64UrlEncoder(EncoderProtocol):
    """URLセーフなBase64エンコーダ。"""

    @classmethod
    def decode(cls, data: bytes) -> bytes:
        """base64でエンコードされたバイトから元のバイトデータにデータをデコードします。

        Args:
            data: デコードするデータ。

        Returns:
            デコードされたデータ。
        """
        try:
            return base64.urlsafe_b64decode(data)
        except ValueError as e:
            raise PydanticCustomError('base64_decode', "Base64 decoding error: '{error}'", {'error': str(e)})

    @classmethod
    def encode(cls, value: bytes) -> bytes:
        """データをバイトからbase64エンコードされたバイトにエンコードします。

        Args:
            value: エンコードするデータ。

        Returns:
            エンコードされたデータ。
        """
        return base64.urlsafe_b64encode(value)

    @classmethod
    def get_json_format(cls) -> Literal['base64url']:
        """エンコードされたデータのJSONフォーマットを取得します。

        Returns:
            エンコードされたデータのJSONフォーマット。
        """
        return 'base64url'

decode classmethod

decode(data: bytes) -> bytes

base64でエンコードされたバイトから元のバイトデータにデータをデコードします。

Parameters:

Name Type Description Default
data bytes

デコードするデータ。

required

Returns:

Type Description
bytes

デコードされたデータ。

Source code in pydantic/types.py
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
@classmethod
def decode(cls, data: bytes) -> bytes:
    """base64でエンコードされたバイトから元のバイトデータにデータをデコードします。

    Args:
        data: デコードするデータ。

    Returns:
        デコードされたデータ。
    """
    try:
        return base64.urlsafe_b64decode(data)
    except ValueError as e:
        raise PydanticCustomError('base64_decode', "Base64 decoding error: '{error}'", {'error': str(e)})

encode classmethod

encode(value: bytes) -> bytes

データをバイトからbase64エンコードされたバイトにエンコードします。

Parameters:

Name Type Description Default
value bytes

エンコードするデータ。

required

Returns:

Type Description
bytes

エンコードされたデータ。

Source code in pydantic/types.py
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
@classmethod
def encode(cls, value: bytes) -> bytes:
    """データをバイトからbase64エンコードされたバイトにエンコードします。

    Args:
        value: エンコードするデータ。

    Returns:
        エンコードされたデータ。
    """
    return base64.urlsafe_b64encode(value)

get_json_format classmethod

get_json_format() -> Literal['base64url']

エンコードされたデータのJSONフォーマットを取得します。

Returns:

Type Description
Literal['base64url']

エンコードされたデータのJSONフォーマット。

Source code in pydantic/types.py
2249
2250
2251
2252
2253
2254
2255
2256
@classmethod
def get_json_format(cls) -> Literal['base64url']:
    """エンコードされたデータのJSONフォーマットを取得します。

    Returns:
        エンコードされたデータのJSONフォーマット。
    """
    return 'base64url'

EncodedBytes dataclass

指定されたエンコーダを使用してエンコードおよびデコードされるバイトタイプ。

EncodedBytesを動作させるには、EncoderProtocolを実装したエンコーダが必要です。

from typing_extensions import Annotated

from pydantic import BaseModel, EncodedBytes, EncoderProtocol, ValidationError

class MyEncoder(EncoderProtocol):
    @classmethod
    def decode(cls, data: bytes) -> bytes:
        if data == b'**undecodable**':
            raise ValueError('Cannot decode data')
        return data[13:]

    @classmethod
    def encode(cls, value: bytes) -> bytes:
        return b'**encoded**: ' + value

    @classmethod
    def get_json_format(cls) -> str:
        return 'my-encoder'

MyEncodedBytes = Annotated[bytes, EncodedBytes(encoder=MyEncoder)]

class Model(BaseModel):
    my_encoded_bytes: MyEncodedBytes

# Initialize the model with encoded data
m = Model(my_encoded_bytes=b'**encoded**: some bytes')

# Access decoded value
print(m.my_encoded_bytes)
#> b'some bytes'

# Serialize into the encoded form
print(m.model_dump())
#> {'my_encoded_bytes': b'**encoded**: some bytes'}

# Validate encoded data
try:
    Model(my_encoded_bytes=b'**undecodable**')
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    my_encoded_bytes
      Value error, Cannot decode data [type=value_error, input_value=b'**undecodable**', input_type=bytes]
    '''
Source code in pydantic/types.py
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
@_dataclasses.dataclass(**_internal_dataclass.slots_true)
class EncodedBytes:
    """指定されたエンコーダを使用してエンコードおよびデコードされるバイトタイプ。

    `EncodedBytes`を動作させるには、`EncoderProtocol`を実装したエンコーダが必要です。

    ```py
    from typing_extensions import Annotated

    from pydantic import BaseModel, EncodedBytes, EncoderProtocol, ValidationError

    class MyEncoder(EncoderProtocol):
        @classmethod
        def decode(cls, data: bytes) -> bytes:
            if data == b'**undecodable**':
                raise ValueError('Cannot decode data')
            return data[13:]

        @classmethod
        def encode(cls, value: bytes) -> bytes:
            return b'**encoded**: ' + value

        @classmethod
        def get_json_format(cls) -> str:
            return 'my-encoder'

    MyEncodedBytes = Annotated[bytes, EncodedBytes(encoder=MyEncoder)]

    class Model(BaseModel):
        my_encoded_bytes: MyEncodedBytes

    # Initialize the model with encoded data
    m = Model(my_encoded_bytes=b'**encoded**: some bytes')

    # Access decoded value
    print(m.my_encoded_bytes)
    #> b'some bytes'

    # Serialize into the encoded form
    print(m.model_dump())
    #> {'my_encoded_bytes': b'**encoded**: some bytes'}

    # Validate encoded data
    try:
        Model(my_encoded_bytes=b'**undecodable**')
    except ValidationError as e:
        print(e)
        '''
        1 validation error for Model
        my_encoded_bytes
          Value error, Cannot decode data [type=value_error, input_value=b'**undecodable**', input_type=bytes]
        '''
    ```
    """

    encoder: type[EncoderProtocol]

    def __get_pydantic_json_schema__(
        self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
    ) -> JsonSchemaValue:
        field_schema = handler(core_schema)
        field_schema.update(type='string', format=self.encoder.get_json_format())
        return field_schema

    def __get_pydantic_core_schema__(self, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
        return core_schema.with_info_after_validator_function(
            function=self.decode,
            schema=core_schema.bytes_schema(),
            serialization=core_schema.plain_serializer_function_ser_schema(function=self.encode),
        )

    def decode(self, data: bytes, _: core_schema.ValidationInfo) -> bytes:
        """指定されたエンコーダを使用してデータをデコードします。

        Args:
            data: デコードするデータ。

        Returns:
            デコードされたデータ。
        """
        return self.encoder.decode(data)

    def encode(self, value: bytes) -> bytes:
        """指定されたエンコーダを使用してデータをエンコードします。

        Args:
            value: エンコードするデータ。

        Returns:
            エンコードされたデータ。
        """
        return self.encoder.encode(value)

    def __hash__(self) -> int:
        return hash(self.encoder)

decode

decode(data: bytes, _: ValidationInfo) -> bytes

指定されたエンコーダを使用してデータをデコードします。

Parameters:

Name Type Description Default
data bytes

デコードするデータ。

required

Returns:

Type Description
bytes

デコードされたデータ。

Source code in pydantic/types.py
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
def decode(self, data: bytes, _: core_schema.ValidationInfo) -> bytes:
    """指定されたエンコーダを使用してデータをデコードします。

    Args:
        data: デコードするデータ。

    Returns:
        デコードされたデータ。
    """
    return self.encoder.decode(data)

encode

encode(value: bytes) -> bytes

指定されたエンコーダを使用してデータをエンコードします。

Parameters:

Name Type Description Default
value bytes

エンコードするデータ。

required

Returns:

Type Description
bytes

エンコードされたデータ。

Source code in pydantic/types.py
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
def encode(self, value: bytes) -> bytes:
    """指定されたエンコーダを使用してデータをエンコードします。

    Args:
        value: エンコードするデータ。

    Returns:
        エンコードされたデータ。
    """
    return self.encoder.encode(value)

EncodedStr dataclass

Bases: EncodedBytes

指定されたエンコーダを使用してエンコードおよびデコードされるstrタイプ。

EncodedStrを動作させるには、EncoderProtocolを実装したエンコーダが必要です。

from typing_extensions import Annotated

from pydantic import BaseModel, EncodedStr, EncoderProtocol, ValidationError

class MyEncoder(EncoderProtocol):
    @classmethod
    def decode(cls, data: bytes) -> bytes:
        if data == b'**undecodable**':
            raise ValueError('Cannot decode data')
        return data[13:]

    @classmethod
    def encode(cls, value: bytes) -> bytes:
        return b'**encoded**: ' + value

    @classmethod
    def get_json_format(cls) -> str:
        return 'my-encoder'

MyEncodedStr = Annotated[str, EncodedStr(encoder=MyEncoder)]

class Model(BaseModel):
    my_encoded_str: MyEncodedStr

# Initialize the model with encoded data
m = Model(my_encoded_str='**encoded**: some str')

# Access decoded value
print(m.my_encoded_str)
#> some str

# Serialize into the encoded form
print(m.model_dump())
#> {'my_encoded_str': '**encoded**: some str'}

# Validate encoded data
try:
    Model(my_encoded_str='**undecodable**')
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    my_encoded_str
      Value error, Cannot decode data [type=value_error, input_value='**undecodable**', input_type=str]
    '''
Source code in pydantic/types.py
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
@_dataclasses.dataclass(**_internal_dataclass.slots_true)
class EncodedStr(EncodedBytes):
    """指定されたエンコーダを使用してエンコードおよびデコードされるstrタイプ。

    `EncodedStr`を動作させるには、`EncoderProtocol`を実装したエンコーダが必要です。

    ```py
    from typing_extensions import Annotated

    from pydantic import BaseModel, EncodedStr, EncoderProtocol, ValidationError

    class MyEncoder(EncoderProtocol):
        @classmethod
        def decode(cls, data: bytes) -> bytes:
            if data == b'**undecodable**':
                raise ValueError('Cannot decode data')
            return data[13:]

        @classmethod
        def encode(cls, value: bytes) -> bytes:
            return b'**encoded**: ' + value

        @classmethod
        def get_json_format(cls) -> str:
            return 'my-encoder'

    MyEncodedStr = Annotated[str, EncodedStr(encoder=MyEncoder)]

    class Model(BaseModel):
        my_encoded_str: MyEncodedStr

    # Initialize the model with encoded data
    m = Model(my_encoded_str='**encoded**: some str')

    # Access decoded value
    print(m.my_encoded_str)
    #> some str

    # Serialize into the encoded form
    print(m.model_dump())
    #> {'my_encoded_str': '**encoded**: some str'}

    # Validate encoded data
    try:
        Model(my_encoded_str='**undecodable**')
    except ValidationError as e:
        print(e)
        '''
        1 validation error for Model
        my_encoded_str
          Value error, Cannot decode data [type=value_error, input_value='**undecodable**', input_type=str]
        '''
    ```
    """

    def __get_pydantic_core_schema__(self, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
        return core_schema.with_info_after_validator_function(
            function=self.decode_str,
            schema=super(EncodedStr, self).__get_pydantic_core_schema__(source=source, handler=handler),  # noqa: UP008
            serialization=core_schema.plain_serializer_function_ser_schema(function=self.encode_str),
        )

    def decode_str(self, data: bytes, _: core_schema.ValidationInfo) -> str:
        """指定されたエンコーダを使用してデータをデコードします。

        Args:
            data: デコードするデータ。

        Returns:
            デコードされたデータ。
        """
        return data.decode()

    def encode_str(self, value: str) -> str:
        """指定されたエンコーダを使用してデータをエンコードします。

        Args:
            value: エンコードするデータ。

        Returns:
            エンコードされたデータ。
        """
        return super(EncodedStr, self).encode(value=value.encode()).decode()  # noqa: UP008

    def __hash__(self) -> int:
        return hash(self.encoder)

decode_str

decode_str(data: bytes, _: ValidationInfo) -> str

指定されたエンコーダを使用してデータをデコードします。

Parameters:

Name Type Description Default
data bytes

デコードするデータ。

required

Returns:

Type Description
str

デコードされたデータ。

Source code in pydantic/types.py
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
def decode_str(self, data: bytes, _: core_schema.ValidationInfo) -> str:
    """指定されたエンコーダを使用してデータをデコードします。

    Args:
        data: デコードするデータ。

    Returns:
        デコードされたデータ。
    """
    return data.decode()

encode_str

encode_str(value: str) -> str

指定されたエンコーダを使用してデータをエンコードします。

Parameters:

Name Type Description Default
value str

エンコードするデータ。

required

Returns:

Type Description
str

エンコードされたデータ。

Source code in pydantic/types.py
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
def encode_str(self, value: str) -> str:
    """指定されたエンコーダを使用してデータをエンコードします。

    Args:
        value: エンコードするデータ。

    Returns:
        エンコードされたデータ。
    """
    return super(EncodedStr, self).encode(value=value.encode()).decode()  # noqa: UP008

GetPydanticSchema dataclass

pydanticカスタム型フックを提供する注釈を作成するための便利なクラスです。

このクラスは、__get_pydantic_core_schema__および__get_pydantic_json_schema__カスタムフックメソッドを定義するカスタム"マーカー"を作成する必要性をなくすことを目的としています。

例えば、型チェッカーではintとして扱われますが、pydanticではAnyとして扱われるようにするには、次のようにします。

from typing import Any

from typing_extensions import Annotated

from pydantic import BaseModel, GetPydanticSchema

HandleAsAny = GetPydanticSchema(lambda _s, h: h(Any))

class Model(BaseModel):
    x: Annotated[int, HandleAsAny]  # pydantic sees `x: Any`

print(repr(Model(x='abc').x))
#> 'abc'
Source code in pydantic/types.py
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
@_dataclasses.dataclass(**_internal_dataclass.slots_true)
class GetPydanticSchema:
    """Usage docs: https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/types/#using-getpydanticschema-to-reduce-boilerplate

    pydanticカスタム型フックを提供する注釈を作成するための便利なクラスです。

    このクラスは、`__get_pydantic_core_schema__`および`__get_pydantic_json_schema__`カスタムフックメソッドを定義するカスタム"マーカー"を作成する必要性をなくすことを目的としています。

    例えば、型チェッカーでは`int`として扱われますが、pydanticでは`Any`として扱われるようにするには、次のようにします。

    ```python
    from typing import Any

    from typing_extensions import Annotated

    from pydantic import BaseModel, GetPydanticSchema

    HandleAsAny = GetPydanticSchema(lambda _s, h: h(Any))

    class Model(BaseModel):
        x: Annotated[int, HandleAsAny]  # pydantic sees `x: Any`

    print(repr(Model(x='abc').x))
    #> 'abc'
    ```
    """

    get_pydantic_core_schema: Callable[[Any, GetCoreSchemaHandler], CoreSchema] | None = None
    get_pydantic_json_schema: Callable[[Any, GetJsonSchemaHandler], JsonSchemaValue] | None = None

    # Note: we may want to consider adding a convenience staticmethod `def for_type(type_: Any) -> GetPydanticSchema:`
    #   which returns `GetPydanticSchema(lambda _s, h: h(type_))`

    if not TYPE_CHECKING:
        # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access

        def __getattr__(self, item: str) -> Any:
            """Use this rather than defining `__get_pydantic_core_schema__` etc. to reduce the number of nested calls."""
            if item == '__get_pydantic_core_schema__' and self.get_pydantic_core_schema:
                return self.get_pydantic_core_schema
            elif item == '__get_pydantic_json_schema__' and self.get_pydantic_json_schema:
                return self.get_pydantic_json_schema
            else:
                return object.__getattribute__(self, item)

    __hash__ = object.__hash__

Tag dataclass

(呼び出し可能な)識別された結合の場合に使用する、予期されるタグを指定する方法を提供します。

また、エラーメッセージ内のUnionケースにラベルを付ける方法も提供します。

呼び出し可能なDiscriminatorを使用する場合は、Union内の各ケースにTagを付けて、そのケースを識別するために使用するタグを指定します。 例えば、以下の例ではTagを使用して、get_discriminator_value'apple'を返す場合、入力はApplePieとして検証されるべきであり、'pumpkin'を返す場合、入力はPumpkinPieとして検証されるべきであることを指定しています。

ここでのTagの主な役割は、呼び出し可能なDiscriminator関数からの戻り値を、問題のUnionの適切なメンバーにマップすることです。

from typing import Any, Union

from typing_extensions import Annotated, Literal

from pydantic import BaseModel, Discriminator, Tag

class Pie(BaseModel):
    time_to_cook: int
    num_ingredients: int

class ApplePie(Pie):
    fruit: Literal['apple'] = 'apple'

class PumpkinPie(Pie):
    filling: Literal['pumpkin'] = 'pumpkin'

def get_discriminator_value(v: Any) -> str:
    if isinstance(v, dict):
        return v.get('fruit', v.get('filling'))
    return getattr(v, 'fruit', getattr(v, 'filling', None))

class ThanksgivingDinner(BaseModel):
    dessert: Annotated[
        Union[
            Annotated[ApplePie, Tag('apple')],
            Annotated[PumpkinPie, Tag('pumpkin')],
        ],
        Discriminator(get_discriminator_value),
    ]

apple_variation = ThanksgivingDinner.model_validate(
    {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
)
print(repr(apple_variation))
'''
ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
'''

pumpkin_variation = ThanksgivingDinner.model_validate(
    {
        'dessert': {
            'filling': 'pumpkin',
            'time_to_cook': 40,
            'num_ingredients': 6,
        }
    }
)
print(repr(pumpkin_variation))
'''
ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
'''

Note

呼び出し可能なDiscriminatorに関連付けられたTagのすべてのケースに対してTagを指定する必要があります。そうしないと、コードcallable-discriminator-no-tagPydantictUserErrorが発生します。

Tagの使い方の詳細については、Discriminated Unionsconcepts docsを参照してください。

Source code in pydantic/types.py
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
@_dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True)
class Tag:
    """(呼び出し可能な)識別された結合の場合に使用する、予期されるタグを指定する方法を提供します。

    また、エラーメッセージ内のUnionケースにラベルを付ける方法も提供します。

    呼び出し可能な`Discriminator`を使用する場合は、`Union`内の各ケースに`Tag`を付けて、そのケースを識別するために使用するタグを指定します。
    例えば、以下の例では`Tag`を使用して、`get_discriminator_value`が`'apple'`を返す場合、入力は`ApplePie`として検証されるべきであり、`'pumpkin'`を返す場合、入力は`PumpkinPie`として検証されるべきであることを指定しています。

    ここでの`Tag`の主な役割は、呼び出し可能な`Discriminator`関数からの戻り値を、問題の`Union`の適切なメンバーにマップすることです。

    ```py
    from typing import Any, Union

    from typing_extensions import Annotated, Literal

    from pydantic import BaseModel, Discriminator, Tag

    class Pie(BaseModel):
        time_to_cook: int
        num_ingredients: int

    class ApplePie(Pie):
        fruit: Literal['apple'] = 'apple'

    class PumpkinPie(Pie):
        filling: Literal['pumpkin'] = 'pumpkin'

    def get_discriminator_value(v: Any) -> str:
        if isinstance(v, dict):
            return v.get('fruit', v.get('filling'))
        return getattr(v, 'fruit', getattr(v, 'filling', None))

    class ThanksgivingDinner(BaseModel):
        dessert: Annotated[
            Union[
                Annotated[ApplePie, Tag('apple')],
                Annotated[PumpkinPie, Tag('pumpkin')],
            ],
            Discriminator(get_discriminator_value),
        ]

    apple_variation = ThanksgivingDinner.model_validate(
        {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
    )
    print(repr(apple_variation))
    '''
    ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
    '''

    pumpkin_variation = ThanksgivingDinner.model_validate(
        {
            'dessert': {
                'filling': 'pumpkin',
                'time_to_cook': 40,
                'num_ingredients': 6,
            }
        }
    )
    print(repr(pumpkin_variation))
    '''
    ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
    '''
    ```

    !!! note
        呼び出し可能な`Discriminator`に関連付けられた`Tag`のすべてのケースに対して`Tag`を指定する必要があります。そうしないと、コード[`callable-discriminator-no-tag`](../errors/usage_errors.md#callable-discriminator-no-tag)で`PydantictUserError`が発生します。

    `Tag`の使い方の詳細については、[Discriminated Unions]concepts docsを参照してください。

    [Discriminated Unions]: https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/unions.md#discriminated-unions
    """

    tag: str

    def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
        schema = handler(source_type)
        metadata = schema.setdefault('metadata', {})
        assert isinstance(metadata, dict)
        metadata[_core_utils.TAGGED_UNION_TAG_KEY] = self.tag
        return schema

Discriminator dataclass

Union識別子の値を抽出する方法として、カスタムの呼び出し可能オブジェクトを使用する方法を提供します。

これにより、Field(discriminator=<field_name>)から得られるような検証動作を得ることができますが、すべてのUnionの選択にわたって単一の共有フィールドを持つ必要はありません。これにより、識別されたUnionスタイルの検証エラーを持つモデルとプリミティブ型のUnionを処理することも可能になります。 最後に、これにより、識別されたUnionのパフォーマンス上の利点をすべて確認しながら、値が属するUnionのメンバーを識別する方法として、カスタムの呼び出し可能オブジェクトを使用できます。

この例を考えてみましょう。この例では、DiscriminatorTaggedUnionを使用すると、通常のUnionを使用する場合よりもはるかにパフォーマンスが向上します。

from typing import Any, Union

from typing_extensions import Annotated, Literal

from pydantic import BaseModel, Discriminator, Tag

class Pie(BaseModel):
    time_to_cook: int
    num_ingredients: int

class ApplePie(Pie):
    fruit: Literal['apple'] = 'apple'

class PumpkinPie(Pie):
    filling: Literal['pumpkin'] = 'pumpkin'

def get_discriminator_value(v: Any) -> str:
    if isinstance(v, dict):
        return v.get('fruit', v.get('filling'))
    return getattr(v, 'fruit', getattr(v, 'filling', None))

class ThanksgivingDinner(BaseModel):
    dessert: Annotated[
        Union[
            Annotated[ApplePie, Tag('apple')],
            Annotated[PumpkinPie, Tag('pumpkin')],
        ],
        Discriminator(get_discriminator_value),
    ]

apple_variation = ThanksgivingDinner.model_validate(
    {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
)
print(repr(apple_variation))
'''
ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
'''

pumpkin_variation = ThanksgivingDinner.model_validate(
    {
        'dessert': {
            'filling': 'pumpkin',
            'time_to_cook': 40,
            'num_ingredients': 6,
        }
    }
)
print(repr(pumpkin_variation))
'''
ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
'''

Discriminatorの使い方の詳細については、Discriminated Unionsconcepts docsを参照してください。

Source code in pydantic/types.py
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
@_dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True)
class Discriminator:
    """Usage docs: https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/unions/#discriminated-unions-with-callable-discriminator

    Union識別子の値を抽出する方法として、カスタムの呼び出し可能オブジェクトを使用する方法を提供します。

    これにより、`Field(discriminator=<field_name>)`から得られるような検証動作を得ることができますが、すべてのUnionの選択にわたって単一の共有フィールドを持つ必要はありません。これにより、識別されたUnionスタイルの検証エラーを持つモデルとプリミティブ型のUnionを処理することも可能になります。
    最後に、これにより、識別されたUnionのパフォーマンス上の利点をすべて確認しながら、値が属するUnionのメンバーを識別する方法として、カスタムの呼び出し可能オブジェクトを使用できます。

    この例を考えてみましょう。この例では、`Discriminator`と`TaggedUnion`を使用すると、通常の`Union`を使用する場合よりもはるかにパフォーマンスが向上します。

    ```py
    from typing import Any, Union

    from typing_extensions import Annotated, Literal

    from pydantic import BaseModel, Discriminator, Tag

    class Pie(BaseModel):
        time_to_cook: int
        num_ingredients: int

    class ApplePie(Pie):
        fruit: Literal['apple'] = 'apple'

    class PumpkinPie(Pie):
        filling: Literal['pumpkin'] = 'pumpkin'

    def get_discriminator_value(v: Any) -> str:
        if isinstance(v, dict):
            return v.get('fruit', v.get('filling'))
        return getattr(v, 'fruit', getattr(v, 'filling', None))

    class ThanksgivingDinner(BaseModel):
        dessert: Annotated[
            Union[
                Annotated[ApplePie, Tag('apple')],
                Annotated[PumpkinPie, Tag('pumpkin')],
            ],
            Discriminator(get_discriminator_value),
        ]

    apple_variation = ThanksgivingDinner.model_validate(
        {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
    )
    print(repr(apple_variation))
    '''
    ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
    '''

    pumpkin_variation = ThanksgivingDinner.model_validate(
        {
            'dessert': {
                'filling': 'pumpkin',
                'time_to_cook': 40,
                'num_ingredients': 6,
            }
        }
    )
    print(repr(pumpkin_variation))
    '''
    ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
    '''
    ```

    `Discriminator`の使い方の詳細については、[Discriminated Unions]concepts docsを参照してください。

    [Discriminated Unions]: https://yodai-yodai.github.io/translated/pydantic-docs-ja/concepts/unions.md#discriminated-unions
    """

    discriminator: str | Callable[[Any], Hashable]
    """タグ付きUnionの型を識別するための呼び出し可能な名前またはフィールド名。

    "呼び出し可能な"識別子は、入力から識別子の値を抽出する必要があります。
    `str`識別子は、識別するフィールドの名前でなければなりません。
    """
    custom_error_type: str | None = None
    """標準の識別されたUnion検証エラーを置き換える[custom errors](../errors/errors.md#custom-errors)で使用するタイプ。
    """
    custom_error_message: str | None = None
    """カスタムエラーで使用するメッセージ。"""
    custom_error_context: dict[str, int | str | float] | None = None
    """カスタムエラーで使用するコンテキスト。"""

    def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
        origin = _typing_extra.get_origin(source_type)
        if not origin or not _typing_extra.origin_is_union(origin):
            raise TypeError(f'{type(self).__name__} must be used with a Union type, not {source_type}')

        if isinstance(self.discriminator, str):
            from pydantic import Field

            return handler(Annotated[source_type, Field(discriminator=self.discriminator)])
        else:
            original_schema = handler(source_type)
            return self._convert_schema(original_schema)

    def _convert_schema(self, original_schema: core_schema.CoreSchema) -> core_schema.TaggedUnionSchema:
        if original_schema['type'] != 'union':
            # This likely indicates that the schema was a single-item union that was simplified.
            # In this case, we do the same thing we do in
            # `pydantic._internal._discriminated_union._ApplyInferredDiscriminator._apply_to_root`, namely,
            # package the generated schema back into a single-item union.
            original_schema = core_schema.union_schema([original_schema])

        tagged_union_choices = {}
        for i, choice in enumerate(original_schema['choices']):
            tag = None
            if isinstance(choice, tuple):
                choice, tag = choice
            metadata = choice.get('metadata')
            if metadata is not None:
                metadata_tag = metadata.get(_core_utils.TAGGED_UNION_TAG_KEY)
                if metadata_tag is not None:
                    tag = metadata_tag
            if tag is None:
                raise PydanticUserError(
                    f'`Tag` not provided for choice {choice} used with `Discriminator`',
                    code='callable-discriminator-no-tag',
                )
            tagged_union_choices[tag] = choice

        # Have to do these verbose checks to ensure falsy values ('' and {}) don't get ignored
        custom_error_type = self.custom_error_type
        if custom_error_type is None:
            custom_error_type = original_schema.get('custom_error_type')

        custom_error_message = self.custom_error_message
        if custom_error_message is None:
            custom_error_message = original_schema.get('custom_error_message')

        custom_error_context = self.custom_error_context
        if custom_error_context is None:
            custom_error_context = original_schema.get('custom_error_context')

        custom_error_type = original_schema.get('custom_error_type') if custom_error_type is None else custom_error_type
        return core_schema.tagged_union_schema(
            tagged_union_choices,
            self.discriminator,
            custom_error_type=custom_error_type,
            custom_error_message=custom_error_message,
            custom_error_context=custom_error_context,
            strict=original_schema.get('strict'),
            ref=original_schema.get('ref'),
            metadata=original_schema.get('metadata'),
            serialization=original_schema.get('serialization'),
        )

discriminator instance-attribute

discriminator: str | Callable[[Any], Hashable]

タグ付きUnionの型を識別するための呼び出し可能な名前またはフィールド名。

"呼び出し可能な"識別子は、入力から識別子の値を抽出する必要があります。 str識別子は、識別するフィールドの名前でなければなりません。

custom_error_type class-attribute instance-attribute

custom_error_type: str | None = None

標準の識別されたUnion検証エラーを置き換えるcustom errorsで使用するタイプ。

custom_error_message class-attribute instance-attribute

custom_error_message: str | None = None

カスタムエラーで使用するメッセージ。

custom_error_context class-attribute instance-attribute

custom_error_context: (
    dict[str, int | str | float] | None
) = None

カスタムエラーで使用するコンテキスト。

FailFast dataclass

Bases: PydanticMetadata, BaseMetadata

FailFastアノテーションを使用して、最初のエラーで検証を停止するように指定できます。

これは、大量のデータを検証する必要があり、そのデータが有効かどうかを知るだけでよい場合に便利です。

データをより速く検証したい場合は、この設定を有効にすることができます(基本的に、これを使用すると、検証のパフォーマンスが向上しますが、取得する情報が少なくなります)。

from typing import List
from typing_extensions import Annotated
from pydantic import BaseModel, FailFast, ValidationError

class Model(BaseModel):
    x: Annotated[List[int], FailFast()]

# This will raise a single error for the first invalid value and stop validation
try:
    obj = Model(x=[1, 2, 'a', 4, 5, 'b', 7, 8, 9, 'c'])
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    x.2
      Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
    '''
Source code in pydantic/types.py
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
@_dataclasses.dataclass
class FailFast(_fields.PydanticMetadata, BaseMetadata):
    """`FailFast`アノテーションを使用して、最初のエラーで検証を停止するように指定できます。

    これは、大量のデータを検証する必要があり、そのデータが有効かどうかを知るだけでよい場合に便利です。

    データをより速く検証したい場合は、この設定を有効にすることができます(基本的に、これを使用すると、検証のパフォーマンスが向上しますが、取得する情報が少なくなります)。

    ```py
    from typing import List
    from typing_extensions import Annotated
    from pydantic import BaseModel, FailFast, ValidationError

    class Model(BaseModel):
        x: Annotated[List[int], FailFast()]

    # This will raise a single error for the first invalid value and stop validation
    try:
        obj = Model(x=[1, 2, 'a', 4, 5, 'b', 7, 8, 9, 'c'])
    except ValidationError as e:
        print(e)
        '''
        1 validation error for Model
        x.2
          Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
        '''
    ```
    """

    fail_fast: bool = True

conint

conint(
    *,
    strict: bool | None = None,
    gt: int | None = None,
    ge: int | None = None,
    lt: int | None = None,
    le: int | None = None,
    multiple_of: int | None = None
) -> type[int]

Discouraged

この関数は推奨されません。代わりにFieldと共にAnnotatedを使用してください。

この関数はPydantic 3.0で非推奨になります。

その理由は、conintが型を返すため、静的解析ツールではうまく動作しないからです。

from pydantic import BaseModel, conint

class Foo(BaseModel):
    bar: conint(strict=True, gt=0)
from typing_extensions import Annotated

from pydantic import BaseModel, Field

class Foo(BaseModel):
    bar: Annotated[int, Field(strict=True, gt=0)]

追加の制約を可能にするintのラッパ。

Parameters:

Name Type Description Default
strict bool | None

strictモードで整数を検証するかどうか。デフォルトはNoneです。

None
gt int | None

この値より大きい必要があります。

None
ge int | None

この値以上にする必要があります。

None
lt int | None

この値より小さくなければなりません。

None
le int | None

この値以下でなければなりません。

None
multiple_of int | None

値はこのの倍数でなければなりません。

None

Returns:

Type Description
type[int]

ラップされた整数型です。

from pydantic import BaseModel, ValidationError, conint

class ConstrainedExample(BaseModel):
    constrained_int: conint(gt=1)

m = ConstrainedExample(constrained_int=2)
print(repr(m))
#> ConstrainedExample(constrained_int=2)

try:
    ConstrainedExample(constrained_int=0)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than',
            'loc': ('constrained_int',),
            'msg': 'Input should be greater than 1',
            'input': 0,
            'ctx': {'gt': 1},
            'url': 'https://errors.pydantic.dev/2/v/greater_than',
        }
    ]
    '''
Source code in pydantic/types.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def conint(
    *,
    strict: bool | None = None,
    gt: int | None = None,
    ge: int | None = None,
    lt: int | None = None,
    le: int | None = None,
    multiple_of: int | None = None,
) -> type[int]:
    """
    !!! warning "Discouraged"
        この関数は推奨されません。代わりに[`Field`][pydantic.fields.Field]と共に[`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated)を使用してください。

        この関数はPydantic 3.0で**非推奨**になります。

        その理由は、`conint`が型を返すため、静的解析ツールではうまく動作しないからです。

        === ":x: Don't do this"
            ```py
            from pydantic import BaseModel, conint

            class Foo(BaseModel):
                bar: conint(strict=True, gt=0)
            ```

        === ":white_check_mark: Do this"
            ```py
            from typing_extensions import Annotated

            from pydantic import BaseModel, Field

            class Foo(BaseModel):
                bar: Annotated[int, Field(strict=True, gt=0)]
            ```

        追加の制約を可能にする`int`のラッパ。

    Args:
        strict: strictモードで整数を検証するかどうか。デフォルトは`None`です。
        gt: この値より大きい必要があります。
        ge: この値以上にする必要があります。
        lt: この値より小さくなければなりません。
        le: この値以下でなければなりません。
        multiple_of: 値はこのの倍数でなければなりません。

    Returns:
        ラップされた整数型です。

    ```py
    from pydantic import BaseModel, ValidationError, conint

    class ConstrainedExample(BaseModel):
        constrained_int: conint(gt=1)

    m = ConstrainedExample(constrained_int=2)
    print(repr(m))
    #> ConstrainedExample(constrained_int=2)

    try:
        ConstrainedExample(constrained_int=0)
    except ValidationError as e:
        print(e.errors())
        '''
        [
            {
                'type': 'greater_than',
                'loc': ('constrained_int',),
                'msg': 'Input should be greater than 1',
                'input': 0,
                'ctx': {'gt': 1},
                'url': 'https://errors.pydantic.dev/2/v/greater_than',
            }
        ]
        '''
    ```

    """  # noqa: D212
    return Annotated[  # pyright: ignore[reportReturnType]
        int,
        Strict(strict) if strict is not None else None,
        annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
        annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None,
    ]

confloat

confloat(
    *,
    strict: bool | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    multiple_of: float | None = None,
    allow_inf_nan: bool | None = None
) -> type[float]

Discouraged

この関数は推奨されません。代わりにFieldと共にAnnotatedを使用してください。

この関数はPydantic 3.0で非推奨になります。

その理由は、confloatが型を返すため、静的解析ツールではうまく動作しないからです。

from pydantic import BaseModel, confloat

class Foo(BaseModel):
    bar: confloat(strict=True, gt=0)
from typing_extensions import Annotated

from pydantic import BaseModel, Field

class Foo(BaseModel):
    bar: Annotated[float, Field(strict=True, gt=0)]

追加の制約を可能にするfloatのラッパです。

Parameters:

Name Type Description Default
strict bool | None

浮動小数点をstrictモードで検証するかどうか。

None
gt float | None

この値より大きい必要があります。

None
ge float | None

この値以上にする必要があります。

None
lt float | None

この値より小さくなければなりません。

None
le float | None

この値以下でなければなりません。

None
multiple_of float | None

値はこのの倍数でなければなりません。

None
allow_inf_nan bool | None

-infinfnanを許可するかどうか。

None

Returns:

Type Description
type[float]

ラップされたfloat型。

from pydantic import BaseModel, ValidationError, confloat

class ConstrainedExample(BaseModel):
    constrained_float: confloat(gt=1.0)

m = ConstrainedExample(constrained_float=1.1)
print(repr(m))
#> ConstrainedExample(constrained_float=1.1)

try:
    ConstrainedExample(constrained_float=0.9)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than',
            'loc': ('constrained_float',),
            'msg': 'Input should be greater than 1',
            'input': 0.9,
            'ctx': {'gt': 1.0},
            'url': 'https://errors.pydantic.dev/2/v/greater_than',
        }
    ]
    '''
Source code in pydantic/types.py
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
def confloat(
    *,
    strict: bool | None = None,
    gt: float | None = None,
    ge: float | None = None,
    lt: float | None = None,
    le: float | None = None,
    multiple_of: float | None = None,
    allow_inf_nan: bool | None = None,
) -> type[float]:
    """
    !!! warning "Discouraged"
        この関数は推奨されません。代わりに[`Field`][pydantic.fields.Field]と共に[`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated)を使用してください。

        この関数はPydantic 3.0で**非推奨**になります。

        その理由は、`confloat`が型を返すため、静的解析ツールではうまく動作しないからです。

        === ":x: Don't do this"
            ```py
            from pydantic import BaseModel, confloat

            class Foo(BaseModel):
                bar: confloat(strict=True, gt=0)
            ```

        === ":white_check_mark: Do this"
            ```py
            from typing_extensions import Annotated

            from pydantic import BaseModel, Field

            class Foo(BaseModel):
                bar: Annotated[float, Field(strict=True, gt=0)]
            ```

    追加の制約を可能にする`float`のラッパです。

    Args:
        strict: 浮動小数点をstrictモードで検証するかどうか。
        gt: この値より大きい必要があります。
        ge: この値以上にする必要があります。
        lt: この値より小さくなければなりません。
        le: この値以下でなければなりません。
        multiple_of: 値はこのの倍数でなければなりません。
        allow_inf_nan: `-inf`、`inf`、`nan`を許可するかどうか。

    Returns:
        ラップされたfloat型。

    ```py
    from pydantic import BaseModel, ValidationError, confloat

    class ConstrainedExample(BaseModel):
        constrained_float: confloat(gt=1.0)

    m = ConstrainedExample(constrained_float=1.1)
    print(repr(m))
    #> ConstrainedExample(constrained_float=1.1)

    try:
        ConstrainedExample(constrained_float=0.9)
    except ValidationError as e:
        print(e.errors())
        '''
        [
            {
                'type': 'greater_than',
                'loc': ('constrained_float',),
                'msg': 'Input should be greater than 1',
                'input': 0.9,
                'ctx': {'gt': 1.0},
                'url': 'https://errors.pydantic.dev/2/v/greater_than',
            }
        ]
        '''
    ```
    """  # noqa: D212
    return Annotated[  # pyright: ignore[reportReturnType]
        float,
        Strict(strict) if strict is not None else None,
        annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
        annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None,
        AllowInfNan(allow_inf_nan) if allow_inf_nan is not None else None,
    ]

conbytes

conbytes(
    *,
    min_length: int | None = None,
    max_length: int | None = None,
    strict: bool | None = None
) -> type[bytes]

追加の制約を可能にするbytesのラッパ。

Parameters:

Name Type Description Default
min_length int | None

バイトの最小長。

None
max_length int | None

バイトの最大長。

None
strict bool | None

strictモードでバイトを検証するかどうか。

None

Returns:

Type Description
type[bytes]

ラップされたバイトのタイプ。

Source code in pydantic/types.py
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def conbytes(
    *,
    min_length: int | None = None,
    max_length: int | None = None,
    strict: bool | None = None,
) -> type[bytes]:
    """追加の制約を可能にする`bytes`のラッパ。

    Args:
        min_length: バイトの最小長。
        max_length: バイトの最大長。
        strict: strictモードでバイトを検証するかどうか。

    Returns:
        ラップされたバイトのタイプ。
    """
    return Annotated[  # pyright: ignore[reportReturnType]
        bytes,
        Strict(strict) if strict is not None else None,
        annotated_types.Len(min_length or 0, max_length),
    ]

constr

constr(
    *,
    strip_whitespace: bool | None = None,
    to_upper: bool | None = None,
    to_lower: bool | None = None,
    strict: bool | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | Pattern[str] | None = None
) -> type[str]

Discouraged

この関数は推奨されません。代わりにAnnotatedStringConstraintsを使用してください。

この関数はPydantic 3.0で非推奨になります。

その理由は、constrが型を返すため、静的解析ツールではうまく動作しないからです。

from pydantic import BaseModel, constr

class Foo(BaseModel):
    bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')
from typing_extensions import Annotated

from pydantic import BaseModel, StringConstraints

class Foo(BaseModel):
    bar: Annotated[str, StringConstraints(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')]

追加の制約を可能にするstrのラッパ。

from pydantic import BaseModel, constr

class Foo(BaseModel):
    bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')


foo = Foo(bar='  hello  ')
print(foo)
#> bar='HELLO'

Parameters:

Name Type Description Default
strip_whitespace bool | None

先頭と末尾の空白を削除するかどうか。

None
to_upper bool | None

すべての文字を大文字にするかどうか。

None
to_lower bool | None

すべての文字を小文字にするかどうか。

None
strict bool | None

文字列をstrictモードで検証するかどうか。

None
min_length int | None

文字列の最小長。

None
max_length int | None

文字列の最大長。

None
pattern str | Pattern[str] | None

文字列を検証するための正規表現パターン。

None

Returns:

Type Description
type[str]

ラップされた文字列型。

Source code in pydantic/types.py
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
def constr(
    *,
    strip_whitespace: bool | None = None,
    to_upper: bool | None = None,
    to_lower: bool | None = None,
    strict: bool | None = None,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | Pattern[str] | None = None,
) -> type[str]:
    """
    !!! warning "Discouraged"
        この関数は推奨されません。代わりに[`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated)と[`StringConstraints`][pydantic.types.StringConstraints]を使用してください。

        この関数はPydantic 3.0で**非推奨**になります。

        その理由は、`constr`が型を返すため、静的解析ツールではうまく動作しないからです。

        === ":x: Don't do this"
            ```py
            from pydantic import BaseModel, constr

            class Foo(BaseModel):
                bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')
            ```

        === ":white_check_mark: Do this"
            ```py
            from typing_extensions import Annotated

            from pydantic import BaseModel, StringConstraints

            class Foo(BaseModel):
                bar: Annotated[str, StringConstraints(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')]
            ```

    追加の制約を可能にする`str`のラッパ。

    ```py
    from pydantic import BaseModel, constr

    class Foo(BaseModel):
        bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')


    foo = Foo(bar='  hello  ')
    print(foo)
    #> bar='HELLO'
    ```

    Args:
        strip_whitespace: 先頭と末尾の空白を削除するかどうか。
        to_upper: すべての文字を大文字にするかどうか。
        to_lower: すべての文字を小文字にするかどうか。
        strict: 文字列をstrictモードで検証するかどうか。
        min_length: 文字列の最小長。
        max_length: 文字列の最大長。
        pattern: 文字列を検証するための正規表現パターン。

    Returns:
        ラップされた文字列型。
    """  # noqa: D212
    return Annotated[  # pyright: ignore[reportReturnType]
        str,
        StringConstraints(
            strip_whitespace=strip_whitespace,
            to_upper=to_upper,
            to_lower=to_lower,
            strict=strict,
            min_length=min_length,
            max_length=max_length,
            pattern=pattern,
        ),
    ]

conset

conset(
    item_type: type[HashableItemType],
    *,
    min_length: int | None = None,
    max_length: int | None = None
) -> type[set[HashableItemType]]

追加の制約を可能にするtyping.Setのラッパ。

Parameters:

Name Type Description Default
item_type type[HashableItemType]

セット内の項目のタイプ。

required
min_length int | None

セットの最小長。

None
max_length int | None

セットの最大長。

None

Returns:

Type Description
type[set[HashableItemType]]

ラップされたセットのタイプ。

Source code in pydantic/types.py
796
797
798
799
800
801
802
803
804
805
806
807
808
809
def conset(
    item_type: type[HashableItemType], *, min_length: int | None = None, max_length: int | None = None
) -> type[set[HashableItemType]]:
    """追加の制約を可能にする`typing.Set`のラッパ。

    Args:
        item_type: セット内の項目のタイプ。
        min_length: セットの最小長。
        max_length: セットの最大長。

    Returns:
        ラップされたセットのタイプ。
    """
    return Annotated[Set[item_type], annotated_types.Len(min_length or 0, max_length)]  # pyright: ignore[reportReturnType]

confrozenset

confrozenset(
    item_type: type[HashableItemType],
    *,
    min_length: int | None = None,
    max_length: int | None = None
) -> type[frozenset[HashableItemType]]

追加の制約を可能にするtyping.FrozenSetのラッパ。

Parameters:

Name Type Description Default
item_type type[HashableItemType]

FrozenSet内の項目のタイプ。

required
min_length int | None

FrozenSetの最小長。

None
max_length int | None

FrozenSetの最大長。

None

Returns:

Type Description
type[frozenset[HashableItemType]]

ラップされたfrozenset型。

Source code in pydantic/types.py
812
813
814
815
816
817
818
819
820
821
822
823
824
825
def confrozenset(
    item_type: type[HashableItemType], *, min_length: int | None = None, max_length: int | None = None
) -> type[frozenset[HashableItemType]]:
    """追加の制約を可能にする`typing.FrozenSet`のラッパ。

    Args:
        item_type: FrozenSet内の項目のタイプ。
        min_length: FrozenSetの最小長。
        max_length: FrozenSetの最大長。

    Returns:
        ラップされたfrozenset型。
    """
    return Annotated[FrozenSet[item_type], annotated_types.Len(min_length or 0, max_length)]  # pyright: ignore[reportReturnType]

conlist

conlist(
    item_type: type[AnyItemType],
    *,
    min_length: int | None = None,
    max_length: int | None = None,
    unique_items: bool | None = None
) -> type[list[AnyItemType]]

検証を追加するtyping.Listのラッパー。

Parameters:

Name Type Description Default
item_type type[AnyItemType]

リスト内の項目のタイプ。

required
min_length int | None

リストの最小長。デフォルトは"なし"です。

None
max_length int | None

リストの最大長。デフォルトは"なし"です。

None
unique_items bool | None

リスト内のアイテムが一意である必要があるかどうか。デフォルトは"なし"です。

Warning

unique_itemsパラメータは廃止されました。代わりにSetを使用してください。 詳細については、this issueを参照してください。

None

Returns:

Type Description
type[list[AnyItemType]]

ラップされたリストのタイプ。

Source code in pydantic/types.py
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
def conlist(
    item_type: type[AnyItemType],
    *,
    min_length: int | None = None,
    max_length: int | None = None,
    unique_items: bool | None = None,
) -> type[list[AnyItemType]]:
    """検証を追加するtyping.Listのラッパー。

    Args:
        item_type: リスト内の項目のタイプ。
        min_length: リストの最小長。デフォルトは"なし"です。
        max_length: リストの最大長。デフォルトは"なし"です。
        unique_items:リスト内のアイテムが一意である必要があるかどうか。デフォルトは"なし"です。
            !!! warning Deprecated
                `unique_items`パラメータは廃止されました。代わりに`Set`を使用してください。
                詳細については、[this issue](https://github.com/pydantic/pydantic-core/issues/296)を参照してください。

    Returns:
        ラップされたリストのタイプ。
    """
    if unique_items is not None:
        raise PydanticUserError(
            (
                '`unique_items` is removed, use `Set` instead'
                '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)'
            ),
            code='removed-kwargs',
        )
    return Annotated[List[item_type], annotated_types.Len(min_length or 0, max_length)]  # pyright: ignore[reportReturnType]

condecimal

condecimal(
    *,
    strict: bool | None = None,
    gt: int | Decimal | None = None,
    ge: int | Decimal | None = None,
    lt: int | Decimal | None = None,
    le: int | Decimal | None = None,
    multiple_of: int | Decimal | None = None,
    max_digits: int | None = None,
    decimal_places: int | None = None,
    allow_inf_nan: bool | None = None
) -> type[Decimal]

Discouraged

この関数は推奨されません。代わりにFieldと共にAnnotatedを使用してください。

この関数はPydantic 3.0で非推奨になります。

その理由は、condecimalが型を返すため、静的解析ツールではうまく動作しないからです。

from pydantic import BaseModel, condecimal

class Foo(BaseModel):
    bar: condecimal(strict=True, allow_inf_nan=True)
from decimal import Decimal

from typing_extensions import Annotated

from pydantic import BaseModel, Field

class Foo(BaseModel):
    bar: Annotated[Decimal, Field(strict=True, allow_inf_nan=True)]

検証を追加するDecimalのラッパー。

Parameters:

Name Type Description Default
strict bool | None

strictモードで値を検証するかどうか。デフォルトはNoneです。

None
gt int | Decimal | None

この値より大きい必要があります。デフォルトはNoneです。

None
ge int | Decimal | None

この値以上でなければなりません。デフォルトはNoneです。

None
lt int | Decimal | None

値はこれより小さくなければなりません。デフォルトはNoneです。

None
le int | Decimal | None

この値以下でなければなりません。デフォルトはNoneです。

None
multiple_of int | Decimal | None

値はthisの倍数でなければなりません。デフォルトはNoneです。

None
max_digits int | None

最大桁数。デフォルトはNoneです。

None
decimal_places int | None

小数点以下の桁数。デフォルトはNoneです。

None
allow_inf_nan bool | None

無限大とNaNを許可するかどうか。デフォルトはNoneです。

None
from decimal import Decimal

from pydantic import BaseModel, ValidationError, condecimal

class ConstrainedExample(BaseModel):
    constrained_decimal: condecimal(gt=Decimal('1.0'))

m = ConstrainedExample(constrained_decimal=Decimal('1.1'))
print(repr(m))
#> ConstrainedExample(constrained_decimal=Decimal('1.1'))

try:
    ConstrainedExample(constrained_decimal=Decimal('0.9'))
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than',
            'loc': ('constrained_decimal',),
            'msg': 'Input should be greater than 1.0',
            'input': Decimal('0.9'),
            'ctx': {'gt': Decimal('1.0')},
            'url': 'https://errors.pydantic.dev/2/v/greater_than',
        }
    ]
    '''
Source code in pydantic/types.py
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
def condecimal(
    *,
    strict: bool | None = None,
    gt: int | Decimal | None = None,
    ge: int | Decimal | None = None,
    lt: int | Decimal | None = None,
    le: int | Decimal | None = None,
    multiple_of: int | Decimal | None = None,
    max_digits: int | None = None,
    decimal_places: int | None = None,
    allow_inf_nan: bool | None = None,
) -> type[Decimal]:
    """
    !!! warning "Discouraged"
        この関数は推奨されません。代わりに[`Field`][pydantic.fields.Field]と共に[`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated)を使用してください。

        この関数はPydantic 3.0で**非推奨**になります。

        その理由は、`condecimal`が型を返すため、静的解析ツールではうまく動作しないからです。

        === ":x: Don't do this"
            ```py
            from pydantic import BaseModel, condecimal

            class Foo(BaseModel):
                bar: condecimal(strict=True, allow_inf_nan=True)
            ```

        === ":white_check_mark: Do this"
            ```py
            from decimal import Decimal

            from typing_extensions import Annotated

            from pydantic import BaseModel, Field

            class Foo(BaseModel):
                bar: Annotated[Decimal, Field(strict=True, allow_inf_nan=True)]
            ```

    検証を追加するDecimalのラッパー。

    Args:
        strict: strictモードで値を検証するかどうか。デフォルトは`None`です。
        gt: この値より大きい必要があります。デフォルトは`None`です。
        ge: この値以上でなければなりません。デフォルトは`None`です。
        lt: 値はこれより小さくなければなりません。デフォルトは`None`です。
        le: この値以下でなければなりません。デフォルトは`None`です。
        multiple_of: 値はthisの倍数でなければなりません。デフォルトは`None`です。
        max_digits: 最大桁数。デフォルトは`None`です。
        decimal_places: 小数点以下の桁数。デフォルトは`None`です。
        allow_inf_nan: 無限大とNaNを許可するかどうか。デフォルトは`None`です。

    ```py
    from decimal import Decimal

    from pydantic import BaseModel, ValidationError, condecimal

    class ConstrainedExample(BaseModel):
        constrained_decimal: condecimal(gt=Decimal('1.0'))

    m = ConstrainedExample(constrained_decimal=Decimal('1.1'))
    print(repr(m))
    #> ConstrainedExample(constrained_decimal=Decimal('1.1'))

    try:
        ConstrainedExample(constrained_decimal=Decimal('0.9'))
    except ValidationError as e:
        print(e.errors())
        '''
        [
            {
                'type': 'greater_than',
                'loc': ('constrained_decimal',),
                'msg': 'Input should be greater than 1.0',
                'input': Decimal('0.9'),
                'ctx': {'gt': Decimal('1.0')},
                'url': 'https://errors.pydantic.dev/2/v/greater_than',
            }
        ]
        '''
    ```
    """  # noqa: D212
    return Annotated[  # pyright: ignore[reportReturnType]
        Decimal,
        Strict(strict) if strict is not None else None,
        annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
        annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None,
        _fields.pydantic_general_metadata(max_digits=max_digits, decimal_places=decimal_places),
        AllowInfNan(allow_inf_nan) if allow_inf_nan is not None else None,
    ]

condate

condate(
    *,
    strict: bool | None = None,
    gt: date | None = None,
    ge: date | None = None,
    lt: date | None = None,
    le: date | None = None
) -> type[date]

制約を追加する日付のラッパ。

Parameters:

Name Type Description Default
strict bool | None

日付値をstrictモードで検証するかどうか。デフォルトはNoneです。

None
gt date | None

この値より大きい必要があります。デフォルトはNoneです。

None
ge date | None

この値以上でなければなりません。デフォルトはNoneです。

None
lt date | None

値はこれより小さくなければなりません。デフォルトはNoneです。

None
le date | None

この値以下でなければなりません。デフォルトはNoneです。

None

Returns:

Type Description
type[date]

指定された制約を持つ日付型。

Source code in pydantic/types.py
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
def condate(
    *,
    strict: bool | None = None,
    gt: date | None = None,
    ge: date | None = None,
    lt: date | None = None,
    le: date | None = None,
) -> type[date]:
    """制約を追加する日付のラッパ。

    Args:
        strict: 日付値をstrictモードで検証するかどうか。デフォルトは`None`です。
        gt: この値より大きい必要があります。デフォルトは`None`です。
        ge: この値以上でなければなりません。デフォルトは`None`です。
        lt: 値はこれより小さくなければなりません。デフォルトは`None`です。
        le: この値以下でなければなりません。デフォルトは`None`です。

    Returns:
        指定された制約を持つ日付型。
    """
    return Annotated[  # pyright: ignore[reportReturnType]
        date,
        Strict(strict) if strict is not None else None,
        annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
    ]