Pydantic Types
The types module contains custom types used by pydantic.
Bases: TypedDict
Usage docs: https://docs.pydantic.dev/2.2/usage/model_config/
A TypedDict for configuring Pydantic behaviour.
The title for the generated JSON schema, defaults to the model’s name
Type: str | None
Whether to convert all characters to lowercase for str types. Defaults to False.
Type: bool
Whether to convert all characters to uppercase for str types. Defaults to False.
Type: bool
Whether to strip leading and trailing whitespace for str types.
Type: bool
The minimum length for str types. Defaults to None.
Type: int
The maximum length for str types. Defaults to None.
Type: int | None
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
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
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
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
Type: bool
Type: bool
Whether to build models and look up discriminators of tagged unions using python object attributes.
Type: bool
Whether to use the alias for error locs rather than the field’s name. Defaults to True.
Type: bool
A callable that takes a field name and returns an alias for it.
See Alias Generator for details.
Type: Callable[[str], str] | None
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, ...]
Whether to allow infinity (+inf an -inf) and NaN values to float fields. Defaults to True.
Type: bool
A dict or callable to provide extra JSON schema properties. Defaults to None.
Type: dict[str, object] | JsonSchemaExtraCallable | None
A dict of custom JSON encoders for specific types. Defaults to None.
Type: dict[type[object], JsonEncoder] | None
(new in V2) If True, strict validation is applied to all fields on the model.
See Strict Mode for details.
Type: bool
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']
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']
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']
Whether to validate default values during validation. Defaults to False.
Type: bool
whether to validate the return value from call validators.
Type: bool
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, ...]
Whether to hide inputs when printing errors. Defaults to False.
See Hide Input in Errors.
Type: bool
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
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
Bases: PydanticErrorMixin, TypeError
An error raised due to incorrect use of Pydantic.
Bases: PydanticDeprecationWarning
A specific PydanticDeprecationWarning subclass defining functionality deprecated since Pydantic 2.0.
Bases: PydanticMetadata, BaseMetadata
A field metadata class to indicate that a field should be validated in strict mode.
Type: bool Default: True
Bases: PydanticMetadata
A field metadata class to indicate that a field should allow -inf, inf, and nan.
Type: bool Default: True
Bases: GroupedMetadata
Apply constraints to str types.
Type: bool | None Default: None
Type: bool | None Default: None
Type: bool | None Default: None
Type: bool | None Default: None
Type: int | None Default: None
Type: int | None Default: None
Type: str | None Default: None
A type that can be used to import a type from a string.
Type: Literal[1, 3, 4, 5]
Type: Literal['file', 'dir', 'new']
@staticmethod
def validate_file(path: Path, _: core_schema.ValidationInfo) -> Path
Path
@staticmethod
def validate_directory(path: Path, _: core_schema.ValidationInfo) -> Path
Path
@staticmethod
def validate_new(path: Path, _: core_schema.ValidationInfo) -> Path
Path
A special type wrapper which loads JSON before parsing.
Bases: _SecretField[str]
A string that is displayed as ********** in reprs and can be used for passwords.
Bases: _SecretField[bytes]
A bytes that is displayed as ********** in reprs and can be used for passwords.
Bases: str, Enum
Default: 'American Express'
Default: 'Mastercard'
Default: 'Visa'
Default: 'other'
Bases: str
Based on: https://en.wikipedia.org/wiki/Payment_card_number.
Type: bool Default: True
Type: int Default: 12
Type: int Default: 19
Type: str Default: card_number[:6]
Type: str Default: card_number[(-4):]
Type: PaymentCardBrand Default: self.validate_brand(card_number)
Mask all but the last 4 digits of the card number.
Type: str
@classmethod
def validate(
cls,
__input_value: str,
_: core_schema.ValidationInfo,
) -> PaymentCardNumber
Validate the card number and return a PaymentCardNumber instance.
PaymentCardNumber
@classmethod
def validate_digits(cls, card_number: str) -> None
Validate that the card number is all digits.
None
@classmethod
def validate_luhn_check_digit(cls, card_number: str) -> str
Based on: https://en.wikipedia.org/wiki/Luhn_algorithm.
str
@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).
PaymentCardBrand
Bases: int
Converts a bytes string with units to the number of bytes.
def human_readable(decimal: bool = False) -> str
Converts a byte size to a human readable string.
str — A human readable string representation of the byte size.
If True, use decimal units (e.g. 1000 bytes per KB). If False, use binary units (e.g. 1024 bytes per KiB).
def to(unit: str) -> float
Converts a byte size to another unit.
float — The byte size in the new unit.
The unit to convert to. Must be one of the following: B, KB, MB, GB, TB, PB, EiB, KiB, MiB, GiB, TiB, PiB, EiB.
A date in the past.
A date in the future.
A datetime that requires timezone info.
A datetime that doesn’t require timezone info.
A datetime that must be in the past.
A datetime that must be in the future.
Bases: Protocol
Protocol for encoding and decoding data to and from bytes.
@classmethod
def decode(cls, data: bytes) -> bytes
Decode the data using the encoder.
bytes — The decoded data.
The data to decode.
@classmethod
def encode(cls, value: bytes) -> bytes
Encode the data using the encoder.
bytes — The encoded data.
The data to encode.
@classmethod
def get_json_format(cls) -> str
Get the JSON format for the encoded data.
str — The JSON format for the encoded data.
Bases: EncoderProtocol
Base64 encoder.
@classmethod
def decode(cls, data: bytes) -> bytes
Decode the data from base64 encoded bytes to original bytes data.
bytes — The decoded data.
The data to decode.
@classmethod
def encode(cls, value: bytes) -> bytes
Encode the data from bytes to a base64 encoded bytes.
bytes — The encoded data.
The data to encode.
@classmethod
def get_json_format(cls) -> Literal['base64']
Get the JSON format for the encoded data.
Literal['base64'] — The JSON format for the encoded data.
A bytes type that is encoded and decoded using the specified encoder.
Type: type[EncoderProtocol]
def decode(data: bytes, _: core_schema.ValidationInfo) -> bytes
Decode the data using the specified encoder.
bytes — The decoded data.
The data to decode.
def encode(value: bytes) -> bytes
Encode the data using the specified encoder.
bytes — The encoded data.
The data to encode.
Bases: EncodedBytes
A str type that is encoded and decoded using the specified encoder.
def decode_str(data: bytes, _: core_schema.ValidationInfo) -> str
Decode the data using the specified encoder.
str — The decoded data.
The data to decode.
def encode_str(value: str) -> str
Encode the data using the specified encoder.
str — The encoded data.
The data to encode.
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'
Type: Callable[[Any, _annotated_handlers.GetCoreSchemaHandler], CoreSchema] | None Default: None
Type: Callable[[Any, _annotated_handlers.GetJsonSchemaHandler], JsonSchemaValue] | None Default: None
def __getattr__(item: str) -> Any
Use this rather than defining __get_pydantic_core_schema__ etc. to reduce the number of nested calls.
Any
def getattr_migration(module: str) -> Callable[[str], Any]
Implement PEP 562 for objects that were either moved or removed on the migration to V2.
Callable[[str], Any] — A callable that will raise an error if the object is not found.
The module name.
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.
type[int] — The wrapped integer type.
Whether to validate the integer in strict mode. Defaults to None.
The value must be greater than this.
The value must be greater than or equal to this.
The value must be less than this.
The value must be less than or equal to this.
The value must be a multiple of this.
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.
type[float] — The wrapped float type.
Whether to validate the float in strict mode.
The value must be greater than this.
The value must be greater than or equal to this.
The value must be less than this.
The value must be less than or equal to this.
The value must be a multiple of this.
Whether to allow -inf, inf, and nan.
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.
type[bytes] — The wrapped bytes type.
The minimum length of the bytes.
The maximum length of the bytes.
Whether to validate the bytes in strict mode.
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.
type[str] — The wrapped string type.
Whether to strip whitespace from the string.
Whether to convert the string to uppercase.
Whether to convert the string to lowercase.
Whether to validate the string in strict mode.
The minimum length of the string.
The maximum length of the string.
A regex pattern that the string must match.
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.
type[set[HashableItemType]] — The wrapped set type.
The type of the items in the set.
The minimum length of the set.
The maximum length of the set.
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.
type[frozenset[HashableItemType]] — The wrapped frozenset type.
The type of the items in the frozenset.
The minimum length of the frozenset.
The maximum length of the frozenset.
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.
type[list[AnyItemType]] — The wrapped list type.
The type of the items in the list.
The minimum length of the list. Defaults to None.
The maximum length of the list. Defaults to None.
Whether the items in the list must be unique. Defaults to None.
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.
type[Decimal]
Whether to validate the value in strict mode. Defaults to None.
The value must be greater than this. Defaults to None.
The value must be greater than or equal to this. Defaults to None.
The value must be less than this. Defaults to None.
The value must be less than or equal to this. Defaults to None.
The value must be a multiple of this. Defaults to None.
The maximum number of digits. Defaults to None.
The number of decimal places. Defaults to None.
Whether to allow infinity and NaN. Defaults to None.
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.
type[date] — A date type with the specified constraints.
Whether to validate the date value in strict mode. Defaults to None.
The value must be greater than this. Defaults to None.
The value must be greater than or equal to this. Defaults to None.
The value must be less than this. Defaults to None.
The value must be less than or equal to this. Defaults to None.
A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary values.
Default: Dict[str, Any]
A boolean that must be either True or False.
Default: Annotated[bool, Strict()]
An integer that must be greater than zero.
Default: Annotated[int, annotated_types.Gt(0)]
An integer that must be less than zero.
Default: Annotated[int, annotated_types.Lt(0)]
An integer that must be less than or equal to zero.
Default: Annotated[int, annotated_types.Le(0)]
An integer that must be greater than or equal to zero.
Default: Annotated[int, annotated_types.Ge(0)]
An integer that must be validated in strict mode.
Default: Annotated[int, Strict()]
A float that must be greater than zero.
Default: Annotated[float, annotated_types.Gt(0)]
A float that must be less than zero.
Default: Annotated[float, annotated_types.Lt(0)]
A float that must be less than or equal to zero.
Default: Annotated[float, annotated_types.Le(0)]
A float that must be greater than or equal to zero.
Default: Annotated[float, annotated_types.Ge(0)]
A float that must be validated in strict mode.
Default: Annotated[float, Strict(True)]
A float that must be finite (not -inf, inf, or nan).
Default: Annotated[float, AllowInfNan(False)]
A bytes that must be validated in strict mode.
Default: Annotated[bytes, Strict()]
A string that must be validated in strict mode.
Default: Annotated[str, Strict()]
Default: TypeVar('HashableItemType', bound=Hashable)
Default: TypeVar('AnyItemType')
Default: TypeVar('AnyType')
A UUID1 annotated type.
Default: Annotated[UUID, UuidVersion(1)]
A UUID3 annotated type.
Default: Annotated[UUID, UuidVersion(3)]
A UUID4 annotated type.
Default: Annotated[UUID, UuidVersion(4)]
A UUID5 annotated type.
Default: Annotated[UUID, UuidVersion(5)]
A path that must point to a file.
Default: Annotated[Path, PathType('file')]
A path that must point to a directory.
Default: Annotated[Path, PathType('dir')]
A path for a new file or directory that must not already exist.
Default: Annotated[Path, PathType('new')]
Default: TypeVar('SecretType', str, bytes)
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\}
Default: re.compile('^\\s*(\\d*\\.?\\d+)\\s*(\\w+)?', re.IGNORECASE)
A bytes type that is encoded and decoded using the base64 encoder.
Default: Annotated[bytes, EncodedBytes(encoder=Base64Encoder)]
A str type that is encoded and decoded using the base64 encoder.
Default: Annotated[str, EncodedStr(encoder=Base64Encoder)]