Skip to content
You're viewing docs for v2.0. See the latest version →

pydantic.types

The types module contains custom types used by pydantic.

ConfigDict

Bases: TypedDict

A dictionary-like class for configuring Pydantic models.

Attributes

title

Type: str | None

str_to_lower

Type: bool

str_to_upper

Type: bool

str_strip_whitespace

Type: bool

str_min_length

Type: int

str_max_length

Type: int | None

extra

Type: ExtraValues | None

frozen

Type: bool

populate_by_name

Type: bool

use_enum_values

Type: bool

validate_assignment

Type: bool

arbitrary_types_allowed

Type: bool

from_attributes

Type: bool

loc_by_alias

Type: bool

alias_generator

Type: Callable[[str], str] | None

ignored_types

Type: tuple[type, ...]

allow_inf_nan

Type: bool

json_schema_extra

Type: dict[str, object] | JsonSchemaExtraCallable | None

strict

Type: bool

revalidate_instances

Type: Literal['always', 'never', 'subclass-instances']

ser_json_timedelta

Type: Literal['iso8601', 'float']

ser_json_bytes

Type: Literal['utf8', 'base64']

validate_default

Type: bool

validate_return

Type: bool

protected_namespaces

Type: tuple[str, ...]

hide_input_in_errors

Type: bool


PydanticUserError

Bases: PydanticErrorMixin, TypeError

An error raised due to incorrect use of Pydantic.


PydanticDeprecatedSince20

Bases: PydanticDeprecationWarning

A specific PydanticDeprecationWarning subclass defining functionality deprecated since Pydantic 2.0.


Strict

Bases: PydanticMetadata

A field metadata class to indicate that a field should be validated in strict mode.

Attributes

strict

Type: bool Default: True


AllowInfNan

Bases: PydanticMetadata

A field metadata class to indicate that a field should allow -inf, inf, and nan.

Attributes

allow_inf_nan

Type: bool Default: True


ImportString

A type that can be used to import a type from a string.


UuidVersion

Attributes

uuid_version

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

Methods

validate

def validate(value: UUID, _: core_schema.ValidationInfo) -> UUID
Returns

UUID


PathType

Attributes

path_type

Type: Literal['file', 'dir', 'new']

Methods

validate_file

@staticmethod

def validate_file(path: Path, _: core_schema.ValidationInfo) -> Path
Returns

Path

validate_directory

@staticmethod

def validate_directory(path: Path, _: core_schema.ValidationInfo) -> Path
Returns

Path

validate_new

@staticmethod

def validate_new(path: Path, _: core_schema.ValidationInfo) -> Path
Returns

Path


Json

A special type wrapper which loads JSON before parsing.


SecretStr

Bases: _SecretField[str]

A string that is displayed as ********** in reprs and can be used for passwords.


SecretBytes

Bases: _SecretField[bytes]

A bytes that is displayed as ********** in reprs and can be used for passwords.


PaymentCardBrand

Bases: str, Enum

Attributes

amex

Default: 'American Express'

mastercard

Default: 'Mastercard'

visa

Default: 'Visa'

other

Default: 'other'


PaymentCardNumber

Bases: str

Based on: https://en.wikipedia.org/wiki/Payment_card_number.

Attributes

strip_whitespace

Type: bool Default: True

min_length

Type: int Default: 12

max_length

Type: int Default: 19

bin

Type: str Default: card_number[:6]

last4

Type: str Default: card_number[(-4):]

brand

Type: PaymentCardBrand Default: self.validate_brand(card_number)

masked

Mask all but the last 4 digits of the card number.

Type: str

Methods

validate

@classmethod

def validate(
    cls,
    __input_value: str,
    _: core_schema.ValidationInfo,
) -> PaymentCardNumber

Validate the card number and return a PaymentCardNumber instance.

Returns

PaymentCardNumber

validate_digits

@classmethod

def validate_digits(cls, card_number: str) -> None

Validate that the card number is all digits.

Returns

None

validate_luhn_check_digit

@classmethod

def validate_luhn_check_digit(cls, card_number: str) -> str

Based on: https://en.wikipedia.org/wiki/Luhn_algorithm.

Returns

str

validate_brand

@staticmethod

def validate_brand(card_number: str) -> PaymentCardBrand

Validate length based on BIN for major brands: https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN).

Returns

PaymentCardBrand


ByteSize

Bases: int

Converts a bytes string with units to the number of bytes.

Methods

human_readable

def human_readable(decimal: bool = False) -> str

Converts a byte size to a human readable string.

Returns

str — A human readable string representation of the byte size.

Parameters

decimal : bool Default: False

If True, use decimal units (e.g. 1000 bytes per KB). If False, use binary units (e.g. 1024 bytes per KiB).

to

def to(unit: str) -> float

Converts a byte size to another unit.

Returns

float — The byte size in the new unit.

Parameters

unit : str

The unit to convert to. Must be one of the following: B, KB, MB, GB, TB, PB, EiB, KiB, MiB, GiB, TiB, PiB, EiB.


PastDate

A date in the past.


FutureDate

A date in the future.


AwareDatetime

A datetime that requires timezone info.


NaiveDatetime

A datetime that doesn’t require timezone info.


PastDatetime

A datetime that must be in the past.


FutureDatetime

A datetime that must be in the future.


EncoderProtocol

Bases: Protocol

Protocol for encoding and decoding data to and from bytes.

Methods

decode

@classmethod

def decode(cls, data: bytes) -> bytes

Decode the data using the encoder.

Returns

bytes — The decoded data.

Parameters

data : bytes

The data to decode.

encode

@classmethod

def encode(cls, value: bytes) -> bytes

Encode the data using the encoder.

Returns

bytes — The encoded data.

Parameters

value : bytes

The data to encode.

get_json_format

@classmethod

def get_json_format(cls) -> str

Get the JSON format for the encoded data.

Returns

str — The JSON format for the encoded data.


Base64Encoder

Bases: EncoderProtocol

Base64 encoder.

Methods

decode

@classmethod

def decode(cls, data: bytes) -> bytes

Decode the data from base64 encoded bytes to original bytes data.

Returns

bytes — The decoded data.

Parameters

data : bytes

The data to decode.

encode

@classmethod

def encode(cls, value: bytes) -> bytes

Encode the data from bytes to a base64 encoded bytes.

Returns

bytes — The encoded data.

Parameters

value : bytes

The data to encode.

get_json_format

@classmethod

def get_json_format(cls) -> Literal['base64']

Get the JSON format for the encoded data.

Returns

Literal['base64'] — The JSON format for the encoded data.


EncodedBytes

A bytes type that is encoded and decoded using the specified encoder.

Attributes

encoder

Type: type[EncoderProtocol]

Methods

decode

def decode(data: bytes, _: core_schema.ValidationInfo) -> bytes

Decode the data using the specified encoder.

Returns

bytes — The decoded data.

Parameters

data : bytes

The data to decode.

encode

def encode(value: bytes) -> bytes

Encode the data using the specified encoder.

Returns

bytes — The encoded data.

Parameters

value : bytes

The data to encode.


EncodedStr

Bases: EncodedBytes

A str type that is encoded and decoded using the specified encoder.

Methods

decode_str

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

Decode the data using the specified encoder.

Returns

str — The decoded data.

Parameters

data : bytes

The data to decode.

encode_str

def encode_str(value: str) -> str

Encode the data using the specified encoder.

Returns

str — The encoded data.

Parameters

value : str

The data to encode.


GetPydanticSchema

A convenience class for creating an annotation that provides pydantic custom type hooks.

This class is intended to eliminate the need to create a custom “marker” which defines the __get_pydantic_core_schema__ and __get_pydantic_json_schema__ custom hook methods.

For example, to have a field treated by type checkers as int, but by pydantic as Any, you can do:

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'

Attributes

get_pydantic_core_schema

Type: Callable[[Any, _annotated_handlers.GetCoreSchemaHandler], CoreSchema] | None Default: None

get_pydantic_json_schema

Type: Callable[[Any, _annotated_handlers.GetJsonSchemaHandler], JsonSchemaValue] | None Default: None

Methods

getattr

def __getattr__(item: str) -> Any

Use this rather than defining __get_pydantic_core_schema__ etc. to reduce the number of nested calls.

Returns

Any


getattr_migration

def getattr_migration(module: str) -> Callable[[str], Any]

Implement PEP 562 for objects that were either moved or removed on the migration to V2.

Returns

Callable[[str], Any] — A callable that will raise an error if the object is not found.

Parameters

module : str

The module name.


conint

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]

A wrapper around int that allows for additional constraints.

Returns

type[int] — The wrapped integer type.

Parameters

strict : bool | None Default: None

Whether to validate the integer in strict mode. Defaults to None.

gt : int | None Default: None

The value must be greater than this.

ge : int | None Default: None

The value must be greater than or equal to this.

lt : int | None Default: None

The value must be less than this.

le : int | None Default: None

The value must be less than or equal to this.

multiple_of : int | None Default: None

The value must be a multiple of this.


confloat

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]

A wrapper around float that allows for additional constraints.

Returns

type[float] — The wrapped float type.

Parameters

strict : bool | None Default: None

Whether to validate the float in strict mode.

gt : float | None Default: None

The value must be greater than this.

ge : float | None Default: None

The value must be greater than or equal to this.

lt : float | None Default: None

The value must be less than this.

le : float | None Default: None

The value must be less than or equal to this.

multiple_of : float | None Default: None

The value must be a multiple of this.

allow_inf_nan : bool | None Default: None

Whether to allow -inf, inf, and nan.


conbytes

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

A wrapper around bytes that allows for additional constraints.

Returns

type[bytes] — The wrapped bytes type.

Parameters

min_length : int | None Default: None

The minimum length of the bytes.

max_length : int | None Default: None

The maximum length of the bytes.

strict : bool | None Default: None

Whether to validate the bytes in strict mode.


constr

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 | None = None,
) -> type[str]

A wrapper around str that allows for additional constraints.

Returns

type[str] — The wrapped string type.

Parameters

strip_whitespace : bool | None Default: None

Whether to strip whitespace from the string.

to_upper : bool | None Default: None

Whether to convert the string to uppercase.

to_lower : bool | None Default: None

Whether to convert the string to lowercase.

strict : bool | None Default: None

Whether to validate the string in strict mode.

min_length : int | None Default: None

The minimum length of the string.

max_length : int | None Default: None

The maximum length of the string.

pattern : str | None Default: None

A regex pattern that the string must match.


conset

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

A wrapper around typing.Set that allows for additional constraints.

Returns

type[set[HashableItemType]] — The wrapped set type.

Parameters

item_type : type[HashableItemType]

The type of the items in the set.

min_length : int | None Default: None

The minimum length of the set.

max_length : int | None Default: None

The maximum length of the set.


confrozenset

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

A wrapper around typing.FrozenSet that allows for additional constraints.

Returns

type[frozenset[HashableItemType]] — The wrapped frozenset type.

Parameters

item_type : type[HashableItemType]

The type of the items in the frozenset.

min_length : int | None Default: None

The minimum length of the frozenset.

max_length : int | None Default: None

The maximum length of the frozenset.


conlist

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

A wrapper around typing.List that adds validation.

Returns

type[list[AnyItemType]] — The wrapped list type.

Parameters

item_type : type[AnyItemType]

The type of the items in the list.

min_length : int | None Default: None

The minimum length of the list. Defaults to None.

max_length : int | None Default: None

The maximum length of the list. Defaults to None.

unique_items : bool | None Default: None

Whether the items in the list must be unique. Defaults to None.


condecimal

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]

A wrapper around Decimal that adds validation.

Returns

type[Decimal]

Parameters

strict : bool | None Default: None

Whether to validate the value in strict mode. Defaults to None.

gt : int | Decimal | None Default: None

The value must be greater than this. Defaults to None.

ge : int | Decimal | None Default: None

The value must be greater than or equal to this. Defaults to None.

lt : int | Decimal | None Default: None

The value must be less than this. Defaults to None.

le : int | Decimal | None Default: None

The value must be less than or equal to this. Defaults to None.

multiple_of : int | Decimal | None Default: None

The value must be a multiple of this. Defaults to None.

max_digits : int | None Default: None

The maximum number of digits. Defaults to None.

decimal_places : int | None Default: None

The number of decimal places. Defaults to None.

allow_inf_nan : bool | None Default: None

Whether to allow infinity and NaN. Defaults to None.


condate

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

A wrapper for date that adds constraints.

Returns

type[date] — A date type with the specified constraints.

Parameters

strict : bool | None Default: None

Whether to validate the date value in strict mode. Defaults to None.

gt : date | None Default: None

The value must be greater than this. Defaults to None.

ge : date | None Default: None

The value must be greater than or equal to this. Defaults to None.

lt : date | None Default: None

The value must be less than this. Defaults to None.

le : date | None Default: None

The value must be less than or equal to this. Defaults to None.


JsonSchemaValue

A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary values.

Default: Dict[str, Any]

StrictBool

A boolean that must be either True or False.

Default: Annotated[bool, Strict()]

PositiveInt

An integer that must be greater than zero.

Default: Annotated[int, annotated_types.Gt(0)]

NegativeInt

An integer that must be less than zero.

Default: Annotated[int, annotated_types.Lt(0)]

NonPositiveInt

An integer that must be less than or equal to zero.

Default: Annotated[int, annotated_types.Le(0)]

NonNegativeInt

An integer that must be greater than or equal to zero.

Default: Annotated[int, annotated_types.Ge(0)]

StrictInt

An integer that must be validated in strict mode.

Default: Annotated[int, Strict()]

PositiveFloat

A float that must be greater than zero.

Default: Annotated[float, annotated_types.Gt(0)]

NegativeFloat

A float that must be less than zero.

Default: Annotated[float, annotated_types.Lt(0)]

NonPositiveFloat

A float that must be less than or equal to zero.

Default: Annotated[float, annotated_types.Le(0)]

NonNegativeFloat

A float that must be greater than or equal to zero.

Default: Annotated[float, annotated_types.Ge(0)]

StrictFloat

A float that must be validated in strict mode.

Default: Annotated[float, Strict(True)]

FiniteFloat

A float that must be finite (not -inf, inf, or nan).

Default: Annotated[float, AllowInfNan(False)]

StrictBytes

A bytes that must be validated in strict mode.

Default: Annotated[bytes, Strict()]

StrictStr

A string that must be validated in strict mode.

Default: Annotated[str, Strict()]

HashableItemType

Default: TypeVar('HashableItemType', bound=Hashable)

AnyItemType

Default: TypeVar('AnyItemType')

AnyType

Default: TypeVar('AnyType')

UUID1

A UUID1 annotated type.

Default: Annotated[UUID, UuidVersion(1)]

UUID3

A UUID3 annotated type.

Default: Annotated[UUID, UuidVersion(3)]

UUID4

A UUID4 annotated type.

Default: Annotated[UUID, UuidVersion(4)]

UUID5

A UUID5 annotated type.

Default: Annotated[UUID, UuidVersion(5)]

FilePath

A path that must point to a file.

Default: Annotated[Path, PathType('file')]

DirectoryPath

A path that must point to a directory.

Default: Annotated[Path, PathType('dir')]

NewPath

A path for a new file or directory that must not already exist.

Default: Annotated[Path, PathType('new')]

SecretType

Default: TypeVar('SecretType', str, bytes)

BYTE_SIZES

Default: \{'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\}

byte_string_re

Default: re.compile('^\\s*(\\d*\\.?\\d+)\\s*(\\w+)?', re.IGNORECASE)

Base64Bytes

Default: Annotated[bytes, EncodedBytes(encoder=Base64Encoder)]

Base64Str

Default: Annotated[str, EncodedStr(encoder=Base64Encoder)]