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

Pydantic Types

The types module contains custom types used by pydantic.

Strict

Bases: PydanticMetadata, BaseMetadata

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

Attributes

strict

Whether to validate the field in strict mode.

Type: bool

AllowInfNan

Bases: PydanticMetadata

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

StringConstraints

Bases: GroupedMetadata

Apply constraints to str types.

Attributes

strip_whitespace

Whether to strip whitespace from the string.

Type: bool | None

to_upper

Whether to convert the string to uppercase.

Type: bool | None

to_lower

Whether to convert the string to lowercase.

Type: bool | None

strict

Whether to validate the string in strict mode.

Type: bool | None

min_length

The minimum length of the string.

Type: int | None

max_length

The maximum length of the string.

Type: int | None

pattern

A regex pattern that the string must match.

Type: str | None

ImportString

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

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.

PaymentCardNumber

Bases: str

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

Attributes

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.

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'

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.

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()]

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

Base64Bytes

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

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

Base64Str

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

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