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.

from pydantic import BaseModel, PositiveInt, ValidationError

class Model(BaseModel):
    positive_int: PositiveInt

m = Model(positive_int=1)
print(repr(m))
#> Model(positive_int=1)

try:
    Model(positive_int=-1)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than',
            'loc': ('positive_int',),
            'msg': 'Input should be greater than 0',
            'input': -1,
            'ctx': {'gt': 0},
            'url': 'https://errors.pydantic.dev/2/v/greater_than',
        }
    ]
    '''

NegativeInt module-attribute

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

An integer that must be less than zero.

from pydantic import BaseModel, NegativeInt, ValidationError

class Model(BaseModel):
    negative_int: NegativeInt

m = Model(negative_int=-1)
print(repr(m))
#> Model(negative_int=-1)

try:
    Model(negative_int=1)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'less_than',
            'loc': ('negative_int',),
            'msg': 'Input should be less than 0',
            'input': 1,
            'ctx': {'lt': 0},
            'url': 'https://errors.pydantic.dev/2/v/less_than',
        }
    ]
    '''

NonPositiveInt module-attribute

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

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

from pydantic import BaseModel, NonPositiveInt, ValidationError

class Model(BaseModel):
    non_positive_int: NonPositiveInt

m = Model(non_positive_int=0)
print(repr(m))
#> Model(non_positive_int=0)

try:
    Model(non_positive_int=1)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'less_than_equal',
            'loc': ('non_positive_int',),
            'msg': 'Input should be less than or equal to 0',
            'input': 1,
            'ctx': {'le': 0},
            'url': 'https://errors.pydantic.dev/2/v/less_than_equal',
        }
    ]
    '''

NonNegativeInt module-attribute

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

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

from pydantic import BaseModel, NonNegativeInt, ValidationError

class Model(BaseModel):
    non_negative_int: NonNegativeInt

m = Model(non_negative_int=0)
print(repr(m))
#> Model(non_negative_int=0)

try:
    Model(non_negative_int=-1)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than_equal',
            'loc': ('non_negative_int',),
            'msg': 'Input should be greater than or equal to 0',
            'input': -1,
            'ctx': {'ge': 0},
            'url': 'https://errors.pydantic.dev/2/v/greater_than_equal',
        }
    ]
    '''

StrictInt module-attribute

StrictInt = Annotated[int, Strict()]

An integer that must be validated in strict mode.

from pydantic import BaseModel, StrictInt, ValidationError

class StrictIntModel(BaseModel):
    strict_int: StrictInt

try:
    StrictIntModel(strict_int=3.14159)
except ValidationError as e:
    print(e)
    '''
    1 validation error for StrictIntModel
    strict_int
      Input should be a valid integer [type=int_type, input_value=3.14159, input_type=float]
    '''

PositiveFloat module-attribute

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

A float that must be greater than zero.

from pydantic import BaseModel, PositiveFloat, ValidationError

class Model(BaseModel):
    positive_float: PositiveFloat

m = Model(positive_float=1.0)
print(repr(m))
#> Model(positive_float=1.0)

try:
    Model(positive_float=-1.0)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than',
            'loc': ('positive_float',),
            'msg': 'Input should be greater than 0',
            'input': -1.0,
            'ctx': {'gt': 0.0},
            'url': 'https://errors.pydantic.dev/2/v/greater_than',
        }
    ]
    '''

NegativeFloat module-attribute

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

A float that must be less than zero.

from pydantic import BaseModel, NegativeFloat, ValidationError

class Model(BaseModel):
    negative_float: NegativeFloat

m = Model(negative_float=-1.0)
print(repr(m))
#> Model(negative_float=-1.0)

try:
    Model(negative_float=1.0)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'less_than',
            'loc': ('negative_float',),
            'msg': 'Input should be less than 0',
            'input': 1.0,
            'ctx': {'lt': 0.0},
            'url': 'https://errors.pydantic.dev/2/v/less_than',
        }
    ]
    '''

NonPositiveFloat module-attribute

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

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

from pydantic import BaseModel, NonPositiveFloat, ValidationError

class Model(BaseModel):
    non_positive_float: NonPositiveFloat

m = Model(non_positive_float=0.0)
print(repr(m))
#> Model(non_positive_float=0.0)

try:
    Model(non_positive_float=1.0)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'less_than_equal',
            'loc': ('non_positive_float',),
            'msg': 'Input should be less than or equal to 0',
            'input': 1.0,
            'ctx': {'le': 0.0},
            'url': 'https://errors.pydantic.dev/2/v/less_than_equal',
        }
    ]
    '''

NonNegativeFloat module-attribute

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

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

from pydantic import BaseModel, NonNegativeFloat, ValidationError

class Model(BaseModel):
    non_negative_float: NonNegativeFloat

m = Model(non_negative_float=0.0)
print(repr(m))
#> Model(non_negative_float=0.0)

try:
    Model(non_negative_float=-1.0)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than_equal',
            'loc': ('non_negative_float',),
            'msg': 'Input should be greater than or equal to 0',
            'input': -1.0,
            'ctx': {'ge': 0.0},
            'url': 'https://errors.pydantic.dev/2/v/greater_than_equal',
        }
    ]
    '''

StrictFloat module-attribute

StrictFloat = Annotated[float, Strict(True)]

A float that must be validated in strict mode.

from pydantic import BaseModel, StrictFloat, ValidationError

class StrictFloatModel(BaseModel):
    strict_float: StrictFloat

try:
    StrictFloatModel(strict_float='1.0')
except ValidationError as e:
    print(e)
    '''
    1 validation error for StrictFloatModel
    strict_float
      Input should be a valid number [type=float_type, input_value='1.0', input_type=str]
    '''

FiniteFloat module-attribute

FiniteFloat = Annotated[float, AllowInfNan(False)]

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

from pydantic import BaseModel, FiniteFloat

class Model(BaseModel):
    finite: FiniteFloat

m = Model(finite=1.0)
print(m)
#> finite=1.0

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 UUID that must be version 1.

import uuid

from pydantic import BaseModel, UUID1

class Model(BaseModel):
    uuid1: UUID1

Model(uuid1=uuid.uuid1())

UUID3 module-attribute

UUID3 = Annotated[UUID, UuidVersion(3)]

A UUID that must be version 3.

import uuid

from pydantic import BaseModel, UUID3

class Model(BaseModel):
    uuid3: UUID3

Model(uuid3=uuid.uuid3(uuid.NAMESPACE_DNS, 'pydantic.org'))

UUID4 module-attribute

UUID4 = Annotated[UUID, UuidVersion(4)]

A UUID that must be version 4.

import uuid

from pydantic import BaseModel, UUID4

class Model(BaseModel):
    uuid4: UUID4

Model(uuid4=uuid.uuid4())

UUID5 module-attribute

UUID5 = Annotated[UUID, UuidVersion(5)]

A UUID that must be version 5.

import uuid

from pydantic import BaseModel, UUID5

class Model(BaseModel):
    uuid5: UUID5

Model(uuid5=uuid.uuid5(uuid.NAMESPACE_DNS, 'pydantic.org'))

FilePath module-attribute

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

A path that must point to a file.

from pathlib import Path

from pydantic import BaseModel, FilePath, ValidationError

class Model(BaseModel):
    f: FilePath

path = Path('text.txt')
path.touch()
m = Model(f='text.txt')
print(m.model_dump())
#> {'f': PosixPath('text.txt')}
path.unlink()

path = Path('directory')
path.mkdir(exist_ok=True)
try:
    Model(f='directory')  # directory
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    f
      Path does not point to a file [type=path_not_file, input_value='directory', input_type=str]
    '''
path.rmdir()

try:
    Model(f='not-exists-file')
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    f
      Path does not point to a file [type=path_not_file, input_value='not-exists-file', input_type=str]
    '''

DirectoryPath module-attribute

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

A path that must point to a directory.

from pathlib import Path

from pydantic import BaseModel, DirectoryPath, ValidationError

class Model(BaseModel):
    f: DirectoryPath

path = Path('directory/')
path.mkdir()
m = Model(f='directory/')
print(m.model_dump())
#> {'f': PosixPath('directory')}
path.rmdir()

path = Path('file.txt')
path.touch()
try:
    Model(f='file.txt')  # file
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    f
      Path does not point to a directory [type=path_not_directory, input_value='file.txt', input_type=str]
    '''
path.unlink()

try:
    Model(f='not-exists-directory')
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    f
      Path does not point to a directory [type=path_not_directory, input_value='not-exists-directory', input_type=str]
    '''

NewPath module-attribute

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

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

Base64Bytes module-attribute

Base64Bytes = Annotated[
    bytes, EncodedBytes(encoder=Base64Encoder)
]

A bytes type that is encoded and decoded using the standard (non-URL-safe) base64 encoder.

Note

Under the hood, Base64Bytes use standard library base64.encodebytes and base64.decodebytes functions.

As a result, attempting to decode url-safe base64 data using the Base64Bytes type may fail or produce an incorrect decoding.

from pydantic import Base64Bytes, BaseModel, ValidationError

class Model(BaseModel):
    base64_bytes: Base64Bytes

# Initialize the model with base64 data
m = Model(base64_bytes=b'VGhpcyBpcyB0aGUgd2F5')

# Access decoded value
print(m.base64_bytes)
#> b'This is the way'

# Serialize into the base64 form
print(m.model_dump())
#> {'base64_bytes': b'VGhpcyBpcyB0aGUgd2F5
'}

# Validate base64 data
try:
    print(Model(base64_bytes=b'undecodable').base64_bytes)
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    base64_bytes
      Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value=b'undecodable', input_type=bytes]
    '''

Base64Str module-attribute

Base64Str = Annotated[
    str, EncodedStr(encoder=Base64Encoder)
]

A str type that is encoded and decoded using the standard (non-URL-safe) base64 encoder.

Note

Under the hood, Base64Bytes use standard library base64.encodebytes and base64.decodebytes functions.

As a result, attempting to decode url-safe base64 data using the Base64Str type may fail or produce an incorrect decoding.

from pydantic import Base64Str, BaseModel, ValidationError

class Model(BaseModel):
    base64_str: Base64Str

# Initialize the model with base64 data
m = Model(base64_str='VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y')

# Access decoded value
print(m.base64_str)
#> These aren't the droids you're looking for

# Serialize into the base64 form
print(m.model_dump())
#> {'base64_str': 'VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y
'}

# Validate base64 data
try:
    print(Model(base64_str='undecodable').base64_str)
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    base64_str
      Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value='undecodable', input_type=str]
    '''

Base64UrlBytes module-attribute

Base64UrlBytes = Annotated[
    bytes, EncodedBytes(encoder=Base64UrlEncoder)
]

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

Note

Under the hood, Base64UrlBytes use standard library base64.urlsafe_b64encode and base64.urlsafe_b64decode functions.

As a result, the Base64UrlBytes type can be used to faithfully decode "vanilla" base64 data (using '+' and '/').

from pydantic import Base64UrlBytes, BaseModel

class Model(BaseModel):
    base64url_bytes: Base64UrlBytes

# Initialize the model with base64 data
m = Model(base64url_bytes=b'SHc_dHc-TXc==')
print(m)
#> base64url_bytes=b'Hw?tw>Mw'

Base64UrlStr module-attribute

Base64UrlStr = Annotated[
    str, EncodedStr(encoder=Base64UrlEncoder)
]

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

Note

Under the hood, Base64UrlStr use standard library base64.urlsafe_b64encode and base64.urlsafe_b64decode functions.

As a result, the Base64UrlStr type can be used to faithfully decode "vanilla" base64 data (using '+' and '/').

from pydantic import Base64UrlStr, BaseModel

class Model(BaseModel):
    base64url_str: Base64UrlStr

# Initialize the model with base64 data
m = Model(base64url_str='SHc_dHc-TXc==')
print(m)
#> base64url_str='Hw?tw>Mw'

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.

ImportString expects a string and loads the Python object importable at that dotted path. Attributes of modules may be separated from the module by : or ., e.g. if 'math:cos' was provided, the resulting field value would be the functioncos. If a . is used and both an attribute and submodule are present at the same path, the module will be preferred.

On model instantiation, pointers will be evaluated and imported. There is some nuance to this behavior, demonstrated in the examples below.

A known limitation: setting a default value to a string won't result in validation (thus evaluation). This is actively being worked on.

Good behavior:

from math import cos

from pydantic import BaseModel, ImportString, ValidationError


class ImportThings(BaseModel):
    obj: ImportString


# A string value will cause an automatic import
my_cos = ImportThings(obj='math.cos')

# You can use the imported function as you would expect
cos_of_0 = my_cos.obj(0)
assert cos_of_0 == 1


# A string whose value cannot be imported will raise an error
try:
    ImportThings(obj='foo.bar')
except ValidationError as e:
    print(e)
    '''
    1 validation error for ImportThings
    obj
    Invalid python path: No module named 'foo.bar' [type=import_error, input_value='foo.bar', input_type=str]
    '''


# Actual python objects can be assigned as well
my_cos = ImportThings(obj=cos)
my_cos_2 = ImportThings(obj='math.cos')
assert my_cos == my_cos_2

Serializing an ImportString type to json is also possible.

from pydantic import BaseModel, ImportString


class ImportThings(BaseModel):
    obj: ImportString


# Create an instance
m = ImportThings(obj='math:cos')
print(m)
#> obj=<built-in function cos>
print(m.model_dump_json())
#> {"obj":"math.cos"}

UuidVersion dataclass

A field metadata class to indicate a UUID version.

Json

A special type wrapper which loads JSON before parsing.

You can use the Json data type to make Pydantic first load a raw JSON string before validating the loaded data into the parametrized type:

from typing import Any, List

from pydantic import BaseModel, Json, ValidationError


class AnyJsonModel(BaseModel):
    json_obj: Json[Any]


class ConstrainedJsonModel(BaseModel):
    json_obj: Json[List[int]]


print(AnyJsonModel(json_obj='{"b": 1}'))
#> json_obj={'b': 1}
print(ConstrainedJsonModel(json_obj='[1, 2, 3]'))
#> json_obj=[1, 2, 3]

try:
    ConstrainedJsonModel(json_obj=12)
except ValidationError as e:
    print(e)
    '''
    1 validation error for ConstrainedJsonModel
    json_obj
    JSON input should be string, bytes or bytearray [type=json_type, input_value=12, input_type=int]
    '''

try:
    ConstrainedJsonModel(json_obj='[a, b]')
except ValidationError as e:
    print(e)
    '''
    1 validation error for ConstrainedJsonModel
    json_obj
    Invalid JSON: expected value at line 1 column 2 [type=json_invalid, input_value='[a, b]', input_type=str]
    '''

try:
    ConstrainedJsonModel(json_obj='["a", "b"]')
except ValidationError as e:
    print(e)
    '''
    2 validation errors for ConstrainedJsonModel
    json_obj.0
    Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
    json_obj.1
    Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='b', input_type=str]
    '''

When you dump the model using model_dump or model_dump_json, the dumped value will be the result of validation, not the original JSON string. However, you can use the argument round_trip=True to get the original JSON string back:

from typing import List

from pydantic import BaseModel, Json


class ConstrainedJsonModel(BaseModel):
    json_obj: Json[List[int]]


print(ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json())
#> {"json_obj":[1,2,3]}
print(
    ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json(round_trip=True)
)
#> {"json_obj":"[1,2,3]"}

SecretStr

Bases: _SecretField[str]

A string used for storing sensitive information that you do not want to be visible in logging or tracebacks.

It displays '**********' instead of the string value on repr() and str() calls.

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 used for storing sensitive information that you do not want to be visible in logging or tracebacks.

It displays b'**********' instead of the string value on repr() and str() calls.

from pydantic import BaseModel, SecretBytes

class User(BaseModel):
    username: str
    password: SecretBytes

user = User(username='scolvin', password=b'password1')
#> username='scolvin' password=SecretBytes(b'**********')
print(user.password.get_secret_value())
#> b'password1'

PaymentCardNumber

PaymentCardNumber(card_number)

Bases: str

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

Source code in pydantic/types.py
1554
1555
1556
1557
1558
1559
1560
1561
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
1572
1573
1574
1575
@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
1587
1588
1589
1590
1591
@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
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
@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
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
@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 string representing a number of bytes with units (such as '1KB' or '11.5MiB') into an integer.

You can use the ByteSize data type to (case-insensitively) convert a string representation of a number of bytes into an integer, and also to print out human-readable strings representing a number of bytes.

In conformance with IEC 80000-13 Standard we interpret '1KB' to mean 1000 bytes, and '1KiB' to mean 1024 bytes. In general, including a middle 'i' will cause the unit to be interpreted as a power of 2, rather than a power of 10 (so, for example, '1 MB' is treated as 1_000_000 bytes, whereas '1 MiB' is treated as 1_048_576 bytes).

Info

Note that 1b will be parsed as "1 byte" and not "1 bit".

from pydantic import BaseModel, ByteSize

class MyModel(BaseModel):
    size: ByteSize

print(MyModel(size=52000).size)
#> 52000
print(MyModel(size='3000 KiB').size)
#> 3072000

m = MyModel(size='50 PB')
print(m.size.human_readable())
#> 44.4PiB
print(m.size.human_readable(decimal=True))
#> 50.0PB

print(m.size.to('TiB'))
#> 45474.73508864641

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
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
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
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
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
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
@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
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
@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
1973
1974
1975
1976
1977
1978
1979
1980
@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

Standard (non-URL-safe) 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
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
@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
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
@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
2013
2014
2015
2016
2017
2018
2019
2020
@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'

Base64UrlEncoder

Bases: EncoderProtocol

URL-safe 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
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
@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.urlsafe_b64decode(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
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
@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.urlsafe_b64encode(value)

get_json_format classmethod

get_json_format()

Get the JSON format for the encoded data.

Returns:

Type Description
Literal['base64url']

The JSON format for the encoded data.

Source code in pydantic/types.py
2053
2054
2055
2056
2057
2058
2059
2060
@classmethod
def get_json_format(cls) -> Literal['base64url']:
    """Get the JSON format for the encoded data.

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

EncodedBytes dataclass

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

EncodedBytes needs an encoder that implements EncoderProtocol to operate.

from typing_extensions import Annotated

from pydantic import BaseModel, EncodedBytes, EncoderProtocol, ValidationError

class MyEncoder(EncoderProtocol):
    @classmethod
    def decode(cls, data: bytes) -> bytes:
        if data == b'**undecodable**':
            raise ValueError('Cannot decode data')
        return data[13:]

    @classmethod
    def encode(cls, value: bytes) -> bytes:
        return b'**encoded**: ' + value

    @classmethod
    def get_json_format(cls) -> str:
        return 'my-encoder'

MyEncodedBytes = Annotated[bytes, EncodedBytes(encoder=MyEncoder)]

class Model(BaseModel):
    my_encoded_bytes: MyEncodedBytes

# Initialize the model with encoded data
m = Model(my_encoded_bytes=b'**encoded**: some bytes')

# Access decoded value
print(m.my_encoded_bytes)
#> b'some bytes'

# Serialize into the encoded form
print(m.model_dump())
#> {'my_encoded_bytes': b'**encoded**: some bytes'}

# Validate encoded data
try:
    Model(my_encoded_bytes=b'**undecodable**')
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    my_encoded_bytes
      Value error, Cannot decode data [type=value_error, input_value=b'**undecodable**', input_type=bytes]
    '''

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
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
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
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
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 dataclass

Bases: EncodedBytes

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

EncodedStr needs an encoder that implements EncoderProtocol to operate.

from typing_extensions import Annotated

from pydantic import BaseModel, EncodedStr, EncoderProtocol, ValidationError

class MyEncoder(EncoderProtocol):
    @classmethod
    def decode(cls, data: bytes) -> bytes:
        if data == b'**undecodable**':
            raise ValueError('Cannot decode data')
        return data[13:]

    @classmethod
    def encode(cls, value: bytes) -> bytes:
        return b'**encoded**: ' + value

    @classmethod
    def get_json_format(cls) -> str:
        return 'my-encoder'

MyEncodedStr = Annotated[str, EncodedStr(encoder=MyEncoder)]

class Model(BaseModel):
    my_encoded_str: MyEncodedStr

# Initialize the model with encoded data
m = Model(my_encoded_str='**encoded**: some str')

# Access decoded value
print(m.my_encoded_str)
#> some str

# Serialize into the encoded form
print(m.model_dump())
#> {'my_encoded_str': '**encoded**: some str'}

# Validate encoded data
try:
    Model(my_encoded_str='**undecodable**')
except ValidationError as e:
    print(e)
    '''
    1 validation error for Model
    my_encoded_str
      Value error, Cannot decode data [type=value_error, input_value='**undecodable**', input_type=str]
    '''

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
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
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
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
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(EncodedStr, self).encode(value=value.encode()).decode()  # noqa: UP008

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
)

Discouraged

This function is discouraged in favor of using Annotated with Field instead.

This function will be deprecated in Pydantic 3.0.

The reason is that conint returns a type, which doesn't play well with static analysis tools.

from pydantic import BaseModel, conint

class Foo(BaseModel):
    bar: conint(strict=True, gt=0)
from typing_extensions import Annotated

from pydantic import BaseModel, Field

class Foo(BaseModel):
    bar: Annotated[int, Field(strict=True, gt=0)]

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.

from pydantic import BaseModel, ValidationError, conint

class ConstrainedExample(BaseModel):
    constrained_int: conint(gt=1)

m = ConstrainedExample(constrained_int=2)
print(repr(m))
#> ConstrainedExample(constrained_int=2)

try:
    ConstrainedExample(constrained_int=0)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than',
            'loc': ('constrained_int',),
            'msg': 'Input should be greater than 1',
            'input': 0,
            'ctx': {'gt': 1},
            'url': 'https://errors.pydantic.dev/2/v/greater_than',
        }
    ]
    '''
Source code in pydantic/types.py
129
130
131
132
133
134
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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
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]:
    """
    !!! warning "Discouraged"
        This function is **discouraged** in favor of using
        [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
        [`Field`][pydantic.fields.Field] instead.

        This function will be **deprecated** in Pydantic 3.0.

        The reason is that `conint` returns a type, which doesn't play well with static analysis tools.

        === ":x: Don't do this"
            ```py
            from pydantic import BaseModel, conint

            class Foo(BaseModel):
                bar: conint(strict=True, gt=0)
            ```

        === ":white_check_mark: Do this"
            ```py
            from typing_extensions import Annotated

            from pydantic import BaseModel, Field

            class Foo(BaseModel):
                bar: Annotated[int, Field(strict=True, gt=0)]
            ```

    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.

    ```py
    from pydantic import BaseModel, ValidationError, conint

    class ConstrainedExample(BaseModel):
        constrained_int: conint(gt=1)

    m = ConstrainedExample(constrained_int=2)
    print(repr(m))
    #> ConstrainedExample(constrained_int=2)

    try:
        ConstrainedExample(constrained_int=0)
    except ValidationError as e:
        print(e.errors())
        '''
        [
            {
                'type': 'greater_than',
                'loc': ('constrained_int',),
                'msg': 'Input should be greater than 1',
                'input': 0,
                'ctx': {'gt': 1},
                'url': 'https://errors.pydantic.dev/2/v/greater_than',
            }
        ]
        '''
    ```

    """  # noqa: D212
    return Annotated[
        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
)

Discouraged

This function is discouraged in favor of using Annotated with Field instead.

This function will be deprecated in Pydantic 3.0.

The reason is that confloat returns a type, which doesn't play well with static analysis tools.

from pydantic import BaseModel, confloat

class Foo(BaseModel):
    bar: confloat(strict=True, gt=0)
from typing_extensions import Annotated
from pydantic import BaseModel, Field

class Foo(BaseModel):
    bar: Annotated[float, Field(strict=True, gt=0)]

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.

from pydantic import BaseModel, ValidationError, confloat

class ConstrainedExample(BaseModel):
    constrained_float: confloat(gt=1.0)

m = ConstrainedExample(constrained_float=1.1)
print(repr(m))
#> ConstrainedExample(constrained_float=1.1)

try:
    ConstrainedExample(constrained_float=0.9)
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than',
            'loc': ('constrained_float',),
            'msg': 'Input should be greater than 1',
            'input': 0.9,
            'ctx': {'gt': 1.0},
            'url': 'https://errors.pydantic.dev/2/v/greater_than',
        }
    ]
    '''
Source code in pydantic/types.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
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]:
    """
    !!! warning "Discouraged"
        This function is **discouraged** in favor of using
        [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
        [`Field`][pydantic.fields.Field] instead.

        This function will be **deprecated** in Pydantic 3.0.

        The reason is that `confloat` returns a type, which doesn't play well with static analysis tools.

        === ":x: Don't do this"
            ```py
            from pydantic import BaseModel, confloat

            class Foo(BaseModel):
                bar: confloat(strict=True, gt=0)
            ```

        === ":white_check_mark: Do this"
            ```py
            from typing_extensions import Annotated
            from pydantic import BaseModel, Field

            class Foo(BaseModel):
                bar: Annotated[float, Field(strict=True, gt=0)]
            ```

    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.

    ```py
    from pydantic import BaseModel, ValidationError, confloat

    class ConstrainedExample(BaseModel):
        constrained_float: confloat(gt=1.0)

    m = ConstrainedExample(constrained_float=1.1)
    print(repr(m))
    #> ConstrainedExample(constrained_float=1.1)

    try:
        ConstrainedExample(constrained_float=0.9)
    except ValidationError as e:
        print(e.errors())
        '''
        [
            {
                'type': 'greater_than',
                'loc': ('constrained_float',),
                'msg': 'Input should be greater than 1',
                'input': 0.9,
                'ctx': {'gt': 1.0},
                'url': 'https://errors.pydantic.dev/2/v/greater_than',
            }
        ]
        '''
    ```
    """  # noqa: D212
    return Annotated[
        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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
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[
        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
)

Discouraged

This function is discouraged in favor of using Annotated with StringConstraints instead.

This function will be deprecated in Pydantic 3.0.

The reason is that constr returns a type, which doesn't play well with static analysis tools.

from pydantic import BaseModel, constr

class Foo(BaseModel):
    bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')
from pydantic import BaseModel, Annotated, StringConstraints

class Foo(BaseModel):
    bar: Annotated[str, StringConstraints(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')]

A wrapper around str that allows for additional constraints.

from pydantic import BaseModel, constr

class Foo(BaseModel):
    bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')


foo = Foo(bar='  hello  ')
print(foo)
#> bar='HELLO'

Parameters:

Name Type Description Default
strip_whitespace bool | None

Whether to remove leading and trailing whitespace.

None
to_upper bool | None

Whether to turn all characters to uppercase.

None
to_lower bool | None

Whether to turn all characters 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 to validate the string against.

None

Returns:

Type Description
type[str]

The wrapped string type.

Source code in pydantic/types.py
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
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]:
    """
    !!! warning "Discouraged"
        This function is **discouraged** in favor of using
        [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
        [`StringConstraints`][pydantic.types.StringConstraints] instead.

        This function will be **deprecated** in Pydantic 3.0.

        The reason is that `constr` returns a type, which doesn't play well with static analysis tools.

        === ":x: Don't do this"
            ```py
            from pydantic import BaseModel, constr

            class Foo(BaseModel):
                bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')
            ```

        === ":white_check_mark: Do this"
            ```py
            from pydantic import BaseModel, Annotated, StringConstraints

            class Foo(BaseModel):
                bar: Annotated[str, StringConstraints(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')]
            ```

    A wrapper around `str` that allows for additional constraints.

    ```py
    from pydantic import BaseModel, constr

    class Foo(BaseModel):
        bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')


    foo = Foo(bar='  hello  ')
    print(foo)
    #> bar='HELLO'
    ```

    Args:
        strip_whitespace: Whether to remove leading and trailing whitespace.
        to_upper: Whether to turn all characters to uppercase.
        to_lower: Whether to turn all characters 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 to validate the string against.

    Returns:
        The wrapped string type.
    """  # noqa: D212
    return Annotated[
        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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
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[Set[item_type], annotated_types.Len(min_length or 0, max_length)]

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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
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[FrozenSet[item_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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
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[List[item_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
)

Discouraged

This function is discouraged in favor of using Annotated with Field instead.

This function will be deprecated in Pydantic 3.0.

The reason is that condecimal returns a type, which doesn't play well with static analysis tools.

from pydantic import BaseModel, condecimal

class Foo(BaseModel):
    bar: condecimal(strict=True, allow_inf_nan=True)
from decimal import Decimal
from typing_extensions import Annotated

from pydantic import BaseModel, Field

class Foo(BaseModel):
    bar: Annotated[Decimal, Field(strict=True, allow_inf_nan=True)]

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
from decimal import Decimal

from pydantic import BaseModel, ValidationError, condecimal

class ConstrainedExample(BaseModel):
    constrained_decimal: condecimal(gt=Decimal('1.0'))

m = ConstrainedExample(constrained_decimal=Decimal('1.1'))
print(repr(m))
#> ConstrainedExample(constrained_decimal=Decimal('1.1'))

try:
    ConstrainedExample(constrained_decimal=Decimal('0.9'))
except ValidationError as e:
    print(e.errors())
    '''
    [
        {
            'type': 'greater_than',
            'loc': ('constrained_decimal',),
            'msg': 'Input should be greater than 1.0',
            'input': Decimal('0.9'),
            'ctx': {'gt': Decimal('1.0')},
            'url': 'https://errors.pydantic.dev/2/v/greater_than',
        }
    ]
    '''
Source code in pydantic/types.py
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 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
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
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]:
    """
    !!! warning "Discouraged"
        This function is **discouraged** in favor of using
        [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with
        [`Field`][pydantic.fields.Field] instead.

        This function will be **deprecated** in Pydantic 3.0.

        The reason is that `condecimal` returns a type, which doesn't play well with static analysis tools.

        === ":x: Don't do this"
            ```py
            from pydantic import BaseModel, condecimal

            class Foo(BaseModel):
                bar: condecimal(strict=True, allow_inf_nan=True)
            ```

        === ":white_check_mark: Do this"
            ```py
            from decimal import Decimal
            from typing_extensions import Annotated

            from pydantic import BaseModel, Field

            class Foo(BaseModel):
                bar: Annotated[Decimal, Field(strict=True, allow_inf_nan=True)]
            ```

    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`.

    ```py
    from decimal import Decimal

    from pydantic import BaseModel, ValidationError, condecimal

    class ConstrainedExample(BaseModel):
        constrained_decimal: condecimal(gt=Decimal('1.0'))

    m = ConstrainedExample(constrained_decimal=Decimal('1.1'))
    print(repr(m))
    #> ConstrainedExample(constrained_decimal=Decimal('1.1'))

    try:
        ConstrainedExample(constrained_decimal=Decimal('0.9'))
    except ValidationError as e:
        print(e.errors())
        '''
        [
            {
                'type': 'greater_than',
                'loc': ('constrained_decimal',),
                'msg': 'Input should be greater than 1.0',
                'input': Decimal('0.9'),
                'ctx': {'gt': Decimal('1.0')},
                'url': 'https://errors.pydantic.dev/2/v/greater_than',
            }
        ]
        '''
    ```
    """  # noqa: D212
    return Annotated[
        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
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
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[
        date,
        Strict(strict) if strict is not None else None,
        annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le),
    ]