Skip to content

Pydantic Types

The types module contains custom types used by pydantic.

StrictBool module-attribute

StrictBool = Annotated[bool, Strict()]

A boolean that must be either True or False.

PositiveInt module-attribute

PositiveInt = Annotated[int, annotated_types.Gt(0)]

An integer that must be greater than zero.

NegativeInt module-attribute

NegativeInt = Annotated[int, annotated_types.Lt(0)]

An integer that must be less than zero.

NonPositiveInt module-attribute

NonPositiveInt = Annotated[int, annotated_types.Le(0)]

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

NonNegativeInt module-attribute

NonNegativeInt = Annotated[int, annotated_types.Ge(0)]

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

StrictInt module-attribute

StrictInt = Annotated[int, Strict()]

An integer that must be validated in strict mode.

PositiveFloat module-attribute

PositiveFloat = Annotated[float, annotated_types.Gt(0)]

A float that must be greater than zero.

NegativeFloat module-attribute

NegativeFloat = Annotated[float, annotated_types.Lt(0)]

A float that must be less than zero.

NonPositiveFloat module-attribute

NonPositiveFloat = Annotated[float, annotated_types.Le(0)]

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

NonNegativeFloat module-attribute

NonNegativeFloat = Annotated[float, annotated_types.Ge(0)]

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

StrictFloat module-attribute

StrictFloat = Annotated[float, Strict(True)]

A float that must be validated in strict mode.

FiniteFloat module-attribute

FiniteFloat = Annotated[float, AllowInfNan(False)]

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

StrictBytes module-attribute

StrictBytes = Annotated[bytes, Strict()]

A bytes that must be validated in strict mode.

StrictStr module-attribute

StrictStr = Annotated[str, Strict()]

A string that must be validated in strict mode.

UUID1 module-attribute

UUID1 = Annotated[UUID, UuidVersion(1)]

A UUID1 annotated type.

UUID3 module-attribute

UUID3 = Annotated[UUID, UuidVersion(3)]

A UUID3 annotated type.

UUID4 module-attribute

UUID4 = Annotated[UUID, UuidVersion(4)]

A UUID4 annotated type.

UUID5 module-attribute

UUID5 = Annotated[UUID, UuidVersion(5)]

A UUID5 annotated type.

FilePath module-attribute

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

A path that must point to a file.

DirectoryPath module-attribute

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

A path that must point to a directory.

NewPath module-attribute

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

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

Strict dataclass

Bases: _fields.PydanticMetadata, BaseMetadata

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

Attributes:

Name Type Description
strict bool

Whether to validate the field in strict mode.

Example
from typing_extensions import Annotated

from pydantic.types import Strict

StrictBool = Annotated[bool, Strict()]

AllowInfNan dataclass

Bases: _fields.PydanticMetadata

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

StringConstraints dataclass

Bases: annotated_types.GroupedMetadata

Apply constraints to str types.

Attributes:

Name Type Description
strip_whitespace bool | None

Whether to strip whitespace from the string.

to_upper bool | None

Whether to convert the string to uppercase.

to_lower bool | None

Whether to convert the string to lowercase.

strict bool | None

Whether to validate the string in strict mode.

min_length int | None

The minimum length of the string.

max_length int | None

The maximum length of the string.

pattern str | None

A regex pattern that the string must match.

ImportString

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

Example
from datetime import date
from typing import Type

from pydantic import BaseModel, ImportString


class Foo(BaseModel):
    call_date: ImportString[Type[date]]


foo = Foo(call_date="datetime.date")
assert foo.call_date(2021, 1, 1) == date(2021, 1, 1)

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.

Example
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

SecretBytes

Bases: _SecretField[bytes]

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

PaymentCardNumber

PaymentCardNumber(card_number)

Bases: str

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

Source code in pydantic/types.py
842
843
844
845
846
847
848
849
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)

masked property

masked: str

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

Returns:

Type Description
str

A masked card number string.

validate classmethod

validate(__input_value, _)

Validate the card number and return a PaymentCardNumber instance.

Source code in pydantic/types.py
862
863
864
865
@classmethod
def validate(cls, __input_value: str, _: core_schema.ValidationInfo) -> PaymentCardNumber:
    """Validate the card number and return a `PaymentCardNumber` instance."""
    return cls(__input_value)

validate_digits classmethod

validate_digits(card_number)

Validate that the card number is all digits.

Source code in pydantic/types.py
877
878
879
880
881
@classmethod
def validate_digits(cls, card_number: str) -> None:
    """Validate that the card number is all digits."""
    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)

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

Source code in pydantic/types.py
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
@classmethod
def validate_luhn_check_digit(cls, card_number: str) -> str:
    """Based on: 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)

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

Source code in pydantic/types.py
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
@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).
    """
    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

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

human_readable

human_readable(decimal=False)

Converts a byte size to a human readable string.

Parameters:

Name Type Description Default
decimal bool

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

False

Returns:

Type Description
str

A human readable string representation of the byte size.

Source code in pydantic/types.py
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
def human_readable(self, decimal: bool = False) -> str:
    """Converts a byte size to a human readable string.

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

    Returns:
        A human readable string representation of the byte size.
    """
    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}{unit}'
            else:
                return f'{num:0.1f}{unit}'
        num /= divisor

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

to

to(unit)

Converts a byte size to another unit.

Parameters:

Name Type Description Default
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.

required

Returns:

Type Description
float

The byte size in the new unit.

Source code in pydantic/types.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
def to(self, unit: str) -> float:
    """Converts a byte size to another unit.

    Args:
        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.

    Returns:
        The byte size in the new unit.
    """
    try:
        unit_div = BYTE_SIZES[unit.lower()]
    except KeyError:
        raise PydanticCustomError('byte_size_unit', 'Could not interpret byte unit: {unit}', {'unit': unit})

    return self / unit_div

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.

decode classmethod

decode(data)

Decode the data using the encoder.

Parameters:

Name Type Description Default
data bytes

The data to decode.

required

Returns:

Type Description
bytes

The decoded data.

Source code in pydantic/types.py
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
@classmethod
def decode(cls, data: bytes) -> bytes:
    """Decode the data using the encoder.

    Args:
        data: The data to decode.

    Returns:
        The decoded data.
    """
    ...

encode classmethod

encode(value)

Encode the data using the encoder.

Parameters:

Name Type Description Default
value bytes

The data to encode.

required

Returns:

Type Description
bytes

The encoded data.

Source code in pydantic/types.py
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
@classmethod
def encode(cls, value: bytes) -> bytes:
    """Encode the data using the encoder.

    Args:
        value: The data to encode.

    Returns:
        The encoded data.
    """
    ...

get_json_format classmethod

get_json_format()

Get the JSON format for the encoded data.

Returns:

Type Description
str

The JSON format for the encoded data.

Source code in pydantic/types.py
1233
1234
1235
1236
1237
1238
1239
1240
@classmethod
def get_json_format(cls) -> str:
    """Get the JSON format for the encoded data.

    Returns:
        The JSON format for the encoded data.
    """
    ...

Base64Encoder

Bases: EncoderProtocol

Base64 encoder.

decode classmethod

decode(data)

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

Parameters:

Name Type Description Default
data bytes

The data to decode.

required

Returns:

Type Description
bytes

The decoded data.

Source code in pydantic/types.py
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
@classmethod
def decode(cls, data: bytes) -> bytes:
    """Decode the data from base64 encoded bytes to original bytes data.

    Args:
        data: The data to decode.

    Returns:
        The decoded data.
    """
    try:
        return base64.decodebytes(data)
    except ValueError as e:
        raise PydanticCustomError('base64_decode', "Base64 decoding error: '{error}'", {'error': str(e)})

encode classmethod

encode(value)

Encode the data from bytes to a base64 encoded bytes.

Parameters:

Name Type Description Default
value bytes

The data to encode.

required

Returns:

Type Description
bytes

The encoded data.

Source code in pydantic/types.py
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
@classmethod
def encode(cls, value: bytes) -> bytes:
    """Encode the data from bytes to a base64 encoded bytes.

    Args:
        value: The data to encode.

    Returns:
        The encoded data.
    """
    return base64.encodebytes(value)

get_json_format classmethod

get_json_format()

Get the JSON format for the encoded data.

Returns:

Type Description
Literal['base64']

The JSON format for the encoded data.

Source code in pydantic/types.py
1273
1274
1275
1276
1277
1278
1279
1280
@classmethod
def get_json_format(cls) -> Literal['base64']:
    """Get the JSON format for the encoded data.

    Returns:
        The JSON format for the encoded data.
    """
    return 'base64'

EncodedBytes dataclass

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

decode

decode(data, _)

Decode the data using the specified encoder.

Parameters:

Name Type Description Default
data bytes

The data to decode.

required

Returns:

Type Description
bytes

The decoded data.

Source code in pydantic/types.py
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
def decode(self, data: bytes, _: core_schema.ValidationInfo) -> bytes:
    """Decode the data using the specified encoder.

    Args:
        data: The data to decode.

    Returns:
        The decoded data.
    """
    return self.encoder.decode(data)

encode

encode(value)

Encode the data using the specified encoder.

Parameters:

Name Type Description Default
value bytes

The data to encode.

required

Returns:

Type Description
bytes

The encoded data.

Source code in pydantic/types.py
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
def encode(self, value: bytes) -> bytes:
    """Encode the data using the specified encoder.

    Args:
        value: The data to encode.

    Returns:
        The encoded data.
    """
    return self.encoder.encode(value)

EncodedStr

Bases: EncodedBytes

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

decode_str

decode_str(data, _)

Decode the data using the specified encoder.

Parameters:

Name Type Description Default
data bytes

The data to decode.

required

Returns:

Type Description
str

The decoded data.

Source code in pydantic/types.py
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
def decode_str(self, data: bytes, _: core_schema.ValidationInfo) -> str:
    """Decode the data using the specified encoder.

    Args:
        data: The data to decode.

    Returns:
        The decoded data.
    """
    return data.decode()

encode_str

encode_str(value)

Encode the data using the specified encoder.

Parameters:

Name Type Description Default
value str

The data to encode.

required

Returns:

Type Description
str

The encoded data.

Source code in pydantic/types.py
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
def encode_str(self, value: str) -> str:
    """Encode the data using the specified encoder.

    Args:
        value: The data to encode.

    Returns:
        The encoded data.
    """
    return super().encode(value=value.encode()).decode()

GetPydanticSchema dataclass

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

conint(
    *,
    strict=None,
    gt=None,
    ge=None,
    lt=None,
    le=None,
    multiple_of=None
)

A wrapper around int that allows for additional constraints.

Parameters:

Name Type Description Default
strict bool | None

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

None
gt int | None

The value must be greater than this.

None
ge int | None

The value must be greater than or equal to this.

None
lt int | None

The value must be less than this.

None
le int | None

The value must be less than or equal to this.

None
multiple_of int | None

The value must be a multiple of this.

None

Returns:

Type Description
type[int]

The wrapped integer type.

Source code in pydantic/types.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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.

    Args:
        strict: Whether to validate the integer in strict mode. Defaults to `None`.
        gt: The value must be greater than this.
        ge: The value must be greater than or equal to this.
        lt: The value must be less than this.
        le: The value must be less than or equal to this.
        multiple_of: The value must be a multiple of this.

    Returns:
        The wrapped integer type.
    """
    return Annotated[  # type: ignore[return-value]
        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=None,
    gt=None,
    ge=None,
    lt=None,
    le=None,
    multiple_of=None,
    allow_inf_nan=None
)

A wrapper around float that allows for additional constraints.

Parameters:

Name Type Description Default
strict bool | None

Whether to validate the float in strict mode.

None
gt float | None

The value must be greater than this.

None
ge float | None

The value must be greater than or equal to this.

None
lt float | None

The value must be less than this.

None
le float | None

The value must be less than or equal to this.

None
multiple_of float | None

The value must be a multiple of this.

None
allow_inf_nan bool | None

Whether to allow -inf, inf, and nan.

None

Returns:

Type Description
type[float]

The wrapped float type.

Source code in pydantic/types.py
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
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.

    Args:
        strict: Whether to validate the float in strict mode.
        gt: The value must be greater than this.
        ge: The value must be greater than or equal to this.
        lt: The value must be less than this.
        le: The value must be less than or equal to this.
        multiple_of: The value must be a multiple of this.
        allow_inf_nan: Whether to allow `-inf`, `inf`, and `nan`.

    Returns:
        The wrapped float type.
    """
    return Annotated[  # type: ignore[return-value]
        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=None, max_length=None, strict=None)

A wrapper around bytes that allows for additional constraints.

Parameters:

Name Type Description Default
min_length int | None

The minimum length of the bytes.

None
max_length int | None

The maximum length of the bytes.

None
strict bool | None

Whether to validate the bytes in strict mode.

None

Returns:

Type Description
type[bytes]

The wrapped bytes type.

Source code in pydantic/types.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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.

    Args:
        min_length: The minimum length of the bytes.
        max_length: The maximum length of the bytes.
        strict: Whether to validate the bytes in strict mode.

    Returns:
        The wrapped bytes type.
    """
    return Annotated[  # type: ignore[return-value]
        bytes,
        Strict(strict) if strict is not None else None,
        annotated_types.Len(min_length or 0, max_length),
    ]

constr

constr(
    *,
    strip_whitespace=None,
    to_upper=None,
    to_lower=None,
    strict=None,
    min_length=None,
    max_length=None,
    pattern=None
)

A wrapper around str that allows for additional constraints.

Parameters:

Name Type Description Default
strip_whitespace bool | None

Whether to strip whitespace from the string.

None
to_upper bool | None

Whether to convert the string to uppercase.

None
to_lower bool | None

Whether to convert the string to lowercase.

None
strict bool | None

Whether to validate the string in strict mode.

None
min_length int | None

The minimum length of the string.

None
max_length int | None

The maximum length of the string.

None
pattern str | None

A regex pattern that the string must match.

None

Returns:

Type Description
type[str]

The wrapped string type.

Source code in pydantic/types.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
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.

    Args:
        strip_whitespace: Whether to strip whitespace from the string.
        to_upper: Whether to convert the string to uppercase.
        to_lower: Whether to convert the string to lowercase.
        strict: Whether to validate the string in strict mode.
        min_length: The minimum length of the string.
        max_length: The maximum length of the string.
        pattern: A regex pattern that the string must match.

    Returns:
        The wrapped string type.
    """
    return Annotated[  # type: ignore[return-value]
        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, *, min_length=None, max_length=None)

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

Parameters:

Name Type Description Default
item_type type[HashableItemType]

The type of the items in the set.

required
min_length int | None

The minimum length of the set.

None
max_length int | None

The maximum length of the set.

None

Returns:

Type Description
type[set[HashableItemType]]

The wrapped set type.

Source code in pydantic/types.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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.

    Args:
        item_type: The type of the items in the set.
        min_length: The minimum length of the set.
        max_length: The maximum length of the set.

    Returns:
        The wrapped set type.
    """
    return Annotated[  # type: ignore[return-value]
        Set[item_type], annotated_types.Len(min_length or 0, max_length)  # type: ignore[valid-type]
    ]

confrozenset

confrozenset(
    item_type, *, min_length=None, max_length=None
)

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

Parameters:

Name Type Description Default
item_type type[HashableItemType]

The type of the items in the frozenset.

required
min_length int | None

The minimum length of the frozenset.

None
max_length int | None

The maximum length of the frozenset.

None

Returns:

Type Description
type[frozenset[HashableItemType]]

The wrapped frozenset type.

Source code in pydantic/types.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
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.

    Args:
        item_type: The type of the items in the frozenset.
        min_length: The minimum length of the frozenset.
        max_length: The maximum length of the frozenset.

    Returns:
        The wrapped frozenset type.
    """
    return Annotated[  # type: ignore[return-value]
        FrozenSet[item_type],  # type: ignore[valid-type]
        annotated_types.Len(min_length or 0, max_length),
    ]

conlist

conlist(
    item_type,
    *,
    min_length=None,
    max_length=None,
    unique_items=None
)

A wrapper around typing.List that adds validation.

Parameters:

Name Type Description Default
item_type type[AnyItemType]

The type of the items in the list.

required
min_length int | None

The minimum length of the list. Defaults to None.

None
max_length int | None

The maximum length of the list. Defaults to None.

None
unique_items bool | None

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

None

Returns:

Type Description
type[list[AnyItemType]]

The wrapped list type.

Source code in pydantic/types.py
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
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.

    Args:
        item_type: The type of the items in the list.
        min_length: The minimum length of the list. Defaults to None.
        max_length: The maximum length of the list. Defaults to None.
        unique_items: Whether the items in the list must be unique. Defaults to None.

    Returns:
        The wrapped list type.
    """
    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[  # type: ignore[return-value]
        List[item_type],  # type: ignore[valid-type]
        annotated_types.Len(min_length or 0, max_length),
    ]

condecimal

condecimal(
    *,
    strict=None,
    gt=None,
    ge=None,
    lt=None,
    le=None,
    multiple_of=None,
    max_digits=None,
    decimal_places=None,
    allow_inf_nan=None
)

A wrapper around Decimal that adds validation.

Parameters:

Name Type Description Default
strict bool | None

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

None
gt int | Decimal | None

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

None
ge int | Decimal | None

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

None
lt int | Decimal | None

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

None
le int | Decimal | None

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

None
multiple_of int | Decimal | None

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

None
max_digits int | None

The maximum number of digits. Defaults to None.

None
decimal_places int | None

The number of decimal places. Defaults to None.

None
allow_inf_nan bool | None

Whether to allow infinity and NaN. Defaults to None.

None
Source code in pydantic/types.py
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
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.

    Args:
        strict: Whether to validate the value in strict mode. Defaults to `None`.
        gt: The value must be greater than this. Defaults to `None`.
        ge: The value must be greater than or equal to this. Defaults to `None`.
        lt: The value must be less than this. Defaults to `None`.
        le: The value must be less than or equal to this. Defaults to `None`.
        multiple_of: The value must be a multiple of this. Defaults to `None`.
        max_digits: The maximum number of digits. Defaults to `None`.
        decimal_places: The number of decimal places. Defaults to `None`.
        allow_inf_nan: Whether to allow infinity and NaN. Defaults to `None`.
    """
    return Annotated[  # type: ignore[return-value]
        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.PydanticGeneralMetadata(max_digits=max_digits, decimal_places=decimal_places),
        AllowInfNan(allow_inf_nan) if allow_inf_nan is not None else None,
    ]

condate

condate(*, strict=None, gt=None, ge=None, lt=None, le=None)

A wrapper for date that adds constraints.

Parameters:

Name Type Description Default
strict bool | None

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

None
gt date | None

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

None
ge date | None

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

None
lt date | None

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

None
le date | None

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

None

Returns:

Type Description
type[date]

A date type with the specified constraints.

Source code in pydantic/types.py
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
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.

    Args:
        strict: Whether to validate the date value in strict mode. Defaults to `None`.
        gt: The value must be greater than this. Defaults to `None`.
        ge: The value must be greater than or equal to this. Defaults to `None`.
        lt: The value must be less than this. Defaults to `None`.
        le: The value must be less than or equal to this. Defaults to `None`.

    Returns:
        A date type with the specified constraints.
    """
    return Annotated[  # type: ignore[return-value]
        date,
        Strict(strict) if strict is not None else None,
        annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
    ]