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

Pydantic Types

The types module contains custom types used by pydantic.

ConfigDict

Bases: TypedDict

Usage docs: https://docs.pydantic.dev/2.2/usage/model_config/

A TypedDict for configuring Pydantic behaviour.

Attributes

title

The title for the generated JSON schema, defaults to the model’s name

Type: str | None

str_to_lower

Whether to convert all characters to lowercase for str types. Defaults to False.

Type: bool

str_to_upper

Whether to convert all characters to uppercase for str types. Defaults to False.

Type: bool

str_strip_whitespace

Whether to strip leading and trailing whitespace for str types.

Type: bool

str_min_length

The minimum length for str types. Defaults to None.

Type: int

str_max_length

The maximum length for str types. Defaults to None.

Type: int | None

extra

Whether to ignore, allow, or forbid extra attributes during model initialization.

The value must be a ExtraValues string. Defaults to 'ignore'.

See Extra Attributes for details.

Type: ExtraValues | None

frozen

Whether or not models are faux-immutable, i.e. whether __setattr__ is allowed, and also generates a __hash__() method for the model. This makes instances of the model potentially hashable if all the attributes are hashable. Defaults to False.

Type: bool

populate_by_name

Whether an aliased field may be populated by its name as given by the model attribute, as well as the alias. Defaults to False.

Type: bool

use_enum_values

Whether to populate models with the value property of enums, rather than the raw enum. This may be useful if you want to serialize model.model_dump() later. Defaults to False.

Type: bool

validate_assignment

Type: bool

arbitrary_types_allowed

Type: bool

from_attributes

Whether to build models and look up discriminators of tagged unions using python object attributes.

Type: bool

loc_by_alias

Whether to use the alias for error locs rather than the field’s name. Defaults to True.

Type: bool

alias_generator

A callable that takes a field name and returns an alias for it.

See Alias Generator for details.

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

ignored_types

A tuple of types that may occur as values of class attributes without annotations. This is typically used for custom descriptors (classes that behave like property). If an attribute is set on a class without an annotation and has a type that is not in this tuple (or otherwise recognized by pydantic), an error will be raised. Defaults to ().

Type: tuple[type, ...]

allow_inf_nan

Whether to allow infinity (+inf an -inf) and NaN values to float fields. Defaults to True.

Type: bool

json_schema_extra

A dict or callable to provide extra JSON schema properties. Defaults to None.

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

json_encoders

A dict of custom JSON encoders for specific types. Defaults to None.

Type: dict[type[object], JsonEncoder] | None

strict

(new in V2) If True, strict validation is applied to all fields on the model. See Strict Mode for details.

Type: bool

revalidate_instances

When and how to revalidate models and dataclasses during validation. Accepts the string values of 'never', 'always' and 'subclass-instances'. Defaults to 'never'.

  • 'never' will not revalidate models and dataclasses during validation
  • 'always' will revalidate models and dataclasses during validation
  • 'subclass-instances' will revalidate models and dataclasses during validation if the instance is a subclass of the model or dataclass

See Revalidate Instances for details.

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

ser_json_timedelta

The format of JSON serialized timedeltas. Accepts the string values of 'iso8601' and 'float'. Defaults to 'iso8601'.

  • 'iso8601' will serialize timedeltas to ISO 8601 durations.
  • 'float' will serialize timedeltas to the total number of seconds.

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

ser_json_bytes

The encoding of JSON serialized bytes. Accepts the string values of 'utf8' and 'base64'. Defaults to 'utf8'.

  • 'utf8' will serialize bytes to UTF-8 strings.
  • 'base64' will serialize bytes to URL safe base64 strings.

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

validate_default

Whether to validate default values during validation. Defaults to False.

Type: bool

validate_return

whether to validate the return value from call validators.

Type: bool

protected_namespaces

A tuple of strings that prevent model to have field which conflict with them. Defaults to ('model_', )).

See Protected Namespaces for details.

Type: tuple[str, ...]

hide_input_in_errors

Whether to hide inputs when printing errors. Defaults to False.

See Hide Input in Errors.

Type: bool

defer_build

Whether to defer model validator and serializer construction until the first model validation.

This can be useful to avoid the overhead of building models which are only used nested within other models, or when you want to manually define type namespace via Model.model_rebuild(_types_namespace=...). Defaults to False.

Type: bool

schema_generator

A custom core schema generator class to use when generating JSON schemas. Useful if you want to change the way types are validated across an entire model/schema.

The GenerateSchema interface is subject to change, currently only the string_schema method is public.

See #6737 for details.

Defaults to None.

Type: type[_GenerateSchema] | None


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, BaseMetadata

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


StringConstraints

Bases: GroupedMetadata

Apply constraints to str types.

Attributes

strip_whitespace

Type: bool | None Default: None

to_upper

Type: bool | None Default: None

to_lower

Type: bool | None Default: None

strict

Type: bool | None Default: None

min_length

Type: int | None Default: None

max_length

Type: int | None Default: None

pattern

Type: str | None Default: None


ImportString

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


UuidVersion

Attributes

uuid_version

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


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

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