Pydantic Types
pydantic.types ¶
The types module contains custom types used by pydantic.
StrictBool
module-attribute
¶
A boolean that must be either True
or False
.
PositiveInt
module-attribute
¶
PositiveInt = Annotated[int, 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, 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, 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, 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
¶
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, 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, 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, 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, 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
¶
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
¶
A bytes that must be validated in strict mode.
StrictStr
module-attribute
¶
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 UUID1, BaseModel
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 UUID3, BaseModel
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 UUID4, BaseModel
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 UUID5, BaseModel
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. The parent directory must 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'
JsonValue
module-attribute
¶
JsonValue: TypeAlias = Union[
List["JsonValue"],
Dict[str, "JsonValue"],
str,
bool,
int,
float,
None,
]
A JsonValue
is used to represent a value that can be serialized to JSON.
It may be one of:
List['JsonValue']
Dict[str, 'JsonValue']
str
bool
int
float
None
The following example demonstrates how to use JsonValue
to validate JSON data,
and what kind of errors to expect when input data is not json serializable.
import json
from pydantic import BaseModel, JsonValue, ValidationError
class Model(BaseModel):
j: JsonValue
valid_json_data = {'j': {'a': {'b': {'c': 1, 'd': [2, None]}}}}
invalid_json_data = {'j': {'a': {'b': ...}}}
print(repr(Model.model_validate(valid_json_data)))
#> Model(j={'a': {'b': {'c': 1, 'd': [2, None]}}})
print(repr(Model.model_validate_json(json.dumps(valid_json_data))))
#> Model(j={'a': {'b': {'c': 1, 'd': [2, None]}}})
try:
Model.model_validate(invalid_json_data)
except ValidationError as e:
print(e)
'''
1 validation error for Model
j.dict.a.dict.b
input was not a valid JSON value [type=invalid-json-value, input_value=Ellipsis, input_type=ellipsis]
'''
OnErrorOmit
module-attribute
¶
OnErrorOmit = Annotated[T, _OnErrorOmit]
When used as an item in a list, the key type in a dict, optional values of a TypedDict, etc.
this annotation omits the item from the iteration if there is any error validating it.
That is, instead of a ValidationError
being propagated up and the entire iterable being discarded
any invalid items are discarded and the valid ones are returned.
Strict
dataclass
¶
Bases: PydanticMetadata
, BaseMetadata
Usage Documentation
A field metadata class to indicate that a field should be validated in strict mode.
Use this class as an annotation via Annotated
, as seen below.
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()]
Source code in pydantic/types.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
|
AllowInfNan
dataclass
¶
Bases: PydanticMetadata
A field metadata class to indicate that a field should allow -inf
, inf
, and nan
.
Use this class as an annotation via Annotated
, as seen below.
Attributes:
Name | Type | Description |
---|---|---|
allow_inf_nan |
bool
|
Whether to allow |
Example
```python from typing_extensions import Annotated
from pydantic.types import AllowInfNan
LaxFloat = Annotated[float, AllowInfNan()]
Source code in pydantic/types.py
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
|
StringConstraints
dataclass
¶
Bases: GroupedMetadata
Usage Documentation
A field metadata class to apply constraints to str
types.
Use this class as an annotation via Annotated
, as seen below.
Attributes:
Name | Type | Description |
---|---|---|
strip_whitespace |
bool | None
|
Whether to remove leading and trailing whitespace. |
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 | Pattern[str] | None
|
A regex pattern that the string must match. |
Example
```python from typing_extensions import Annotated
from pydantic.types import StringConstraints
ConstrainedStr = Annotated[str, StringConstraints(min_length=1, max_length=10)]
Source code in pydantic/types.py
688 689 690 691 692 693 694 695 696 697 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 |
|
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.
Good behavior:
import math
from pydantic import BaseModel, Field, 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=math.cos)
my_cos_2 = ImportThings(obj='math.cos')
my_cos_3 = ImportThings(obj='math:cos')
assert my_cos == my_cos_2 == my_cos_3
# You can set default field value either as Python object:
class ImportThingsDefaultPyObj(BaseModel):
obj: ImportString = math.cos
# or as a string value (but only if used with `validate_default=True`)
class ImportThingsDefaultString(BaseModel):
obj: ImportString = Field(default='math.cos', validate_default=True)
my_cos_default1 = ImportThingsDefaultPyObj()
my_cos_default2 = ImportThingsDefaultString()
assert my_cos_default1.obj == my_cos_default2.obj == math.cos
# note: this will not work!
class ImportThingsMissingValidateDefault(BaseModel):
obj: ImportString = 'math.cos'
my_cos_default3 = ImportThingsMissingValidateDefault()
assert my_cos_default3.obj == 'math.cos' # just string, not evaluated
Serializing an ImportString
type to json is also possible.
```py lint="skip" from pydantic import BaseModel, ImportString
class ImportThings(BaseModel): obj: ImportString
Create an instance¶
m = ImportThings(obj='math.cos') print(m)
> obj=¶
print(m.model_dump_json())
>¶
```
Source code in pydantic/types.py
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 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 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 |
|
UuidVersion
dataclass
¶
A field metadata class to indicate a UUID version.
Use this class as an annotation via Annotated
, as seen below.
Attributes:
Name | Type | Description |
---|---|---|
uuid_version |
Literal[1, 3, 4, 5]
|
The version of the UUID. Must be one of 1, 3, 4, or 5. |
Example
from uuid import UUID
from typing_extensions import Annotated
from pydantic.types import UuidVersion
UUID1 = Annotated[UUID, UuidVersion(1)]
Source code in pydantic/types.py
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 |
|
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]"}
Source code in pydantic/types.py
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 |
|
Secret ¶
Bases: _SecretBase[SecretType]
A generic base class used for defining a field with sensitive information that you do not want to be visible in logging or tracebacks.
You may either directly parametrize Secret
with a type, or subclass from Secret
with a parametrized type. The benefit of subclassing
is that you can define a custom _display
method, which will be used for repr()
and str()
methods. The examples below demonstrate both
ways of using Secret
to create a new secret type.
- Directly parametrizing
Secret
with a type:
from pydantic import BaseModel, Secret
SecretBool = Secret[bool]
class Model(BaseModel):
secret_bool: SecretBool
m = Model(secret_bool=True)
print(m.model_dump())
#> {'secret_bool': Secret('**********')}
print(m.model_dump_json())
#> {"secret_bool":"**********"}
print(m.secret_bool.get_secret_value())
#> True
- Subclassing from parametrized
Secret
:
from datetime import date
from pydantic import BaseModel, Secret
class SecretDate(Secret[date]):
def _display(self) -> str:
return '****/**/**'
class Model(BaseModel):
secret_date: SecretDate
m = Model(secret_date=date(2022, 1, 1))
print(m.model_dump())
#> {'secret_date': SecretDate('****/**/**')}
print(m.model_dump_json())
#> {"secret_date":"****/**/**"}
print(m.secret_date.get_secret_value())
#> 2022-01-01
The value returned by the _display
method will be used for repr()
and str()
.
You can enforce constraints on the underlying type through annotations: For example:
from typing_extensions import Annotated
from pydantic import BaseModel, Field, Secret, ValidationError
SecretPosInt = Secret[Annotated[int, Field(gt=0, strict=True)]]
class Model(BaseModel):
sensitive_int: SecretPosInt
m = Model(sensitive_int=42)
print(m.model_dump())
#> {'sensitive_int': Secret('**********')}
try:
m = Model(sensitive_int=-42) # (1)!
except ValidationError as exc_info:
print(exc_info.errors(include_url=False, include_input=False))
'''
[
{
'type': 'greater_than',
'loc': ('sensitive_int',),
'msg': 'Input should be greater than 0',
'ctx': {'gt': 0},
}
]
'''
try:
m = Model(sensitive_int='42') # (2)!
except ValidationError as exc_info:
print(exc_info.errors(include_url=False, include_input=False))
'''
[
{
'type': 'int_type',
'loc': ('sensitive_int',),
'msg': 'Input should be a valid integer',
}
]
'''
- The input value is not greater than 0, so it raises a validation error.
- The input value is not an integer, so it raises a validation error because the
SecretPosInt
type has strict mode enabled.
Source code in pydantic/types.py
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 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 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 |
|
SecretStr ¶
Bases: _SecretField[str]
A string used for storing sensitive information that you do not want to be visible in logging or tracebacks.
When the secret value is nonempty, it is displayed as '**********'
instead of the underlying value in
calls to repr()
and str()
. If the value is empty, it is displayed as ''
.
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
print((SecretStr('password'), SecretStr('')))
#> (SecretStr('**********'), SecretStr(''))
As seen above, by default, SecretStr
(and SecretBytes
)
will be serialized as **********
when serializing to json.
You can use the field_serializer
to dump the
secret as plain-text when serializing to json.
from pydantic import BaseModel, SecretBytes, SecretStr, field_serializer
class Model(BaseModel):
password: SecretStr
password_bytes: SecretBytes
@field_serializer('password', 'password_bytes', when_used='json')
def dump_secret(self, v):
return v.get_secret_value()
model = Model(password='IAmSensitive', password_bytes=b'IAmSensitiveBytes')
print(model)
#> password=SecretStr('**********') password_bytes=SecretBytes(b'**********')
print(model.password)
#> **********
print(model.model_dump())
'''
{
'password': SecretStr('**********'),
'password_bytes': SecretBytes(b'**********'),
}
'''
print(model.model_dump_json())
#> {"password":"IAmSensitive","password_bytes":"IAmSensitiveBytes"}
Source code in pydantic/types.py
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 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 |
|
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.
When the secret value is nonempty, it is displayed as b'**********'
instead of the underlying value in
calls to repr()
and str()
. If the value is empty, it is displayed as b''
.
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'
print((SecretBytes(b'password'), SecretBytes(b'')))
#> (SecretBytes(b'**********'), SecretBytes(b''))
Source code in pydantic/types.py
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 |
|
PaymentCardNumber ¶
Bases: str
Based on: https://en.wikipedia.org/wiki/Payment_card_number.
Source code in pydantic/types.py
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 |
|
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: str, /, _: ValidationInfo
) -> PaymentCardNumber
Validate the card number and return a PaymentCardNumber
instance.
Source code in pydantic/types.py
1879 1880 1881 1882 |
|
validate_digits
classmethod
¶
validate_digits(card_number: str) -> None
Validate that the card number is all digits.
Source code in pydantic/types.py
1894 1895 1896 1897 1898 |
|
validate_luhn_check_digit
classmethod
¶
Based on: https://en.wikipedia.org/wiki/Luhn_algorithm.
Source code in pydantic/types.py
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 |
|
validate_brand
staticmethod
¶
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).
Source code in pydantic/types.py
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 |
|
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.human_readable(separator=' '))
#> 44.4 PiB
print(m.size.to('TiB'))
#> 45474.73508864641
Source code in pydantic/types.py
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 |
|
human_readable ¶
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
|
separator |
str
|
A string used to split the value and unit. Defaults to an empty string (''). |
''
|
Returns:
Type | Description |
---|---|
str
|
A human readable string representation of the byte size. |
Source code in pydantic/types.py
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 |
|
to ¶
Converts a byte size to another unit, including both byte and bit units.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
unit |
str
|
The unit to convert to. Must be one of the following: B, KB, MB, GB, TB, PB, EB, KiB, MiB, GiB, TiB, PiB, EiB (byte units) and bit, kbit, mbit, gbit, tbit, pbit, ebit, kibit, mibit, gibit, tibit, pibit, eibit (bit units). |
required |
Returns:
Type | Description |
---|---|
float
|
The byte size in the new unit. |
Source code in pydantic/types.py
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 |
|
PastDate ¶
A date in the past.
Source code in pydantic/types.py
2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 |
|
FutureDate ¶
A date in the future.
Source code in pydantic/types.py
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 |
|
AwareDatetime ¶
A datetime that requires timezone info.
Source code in pydantic/types.py
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 |
|
NaiveDatetime ¶
A datetime that doesn't require timezone info.
Source code in pydantic/types.py
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 |
|
PastDatetime ¶
A datetime that must be in the past.
Source code in pydantic/types.py
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 |
|
FutureDatetime ¶
A datetime that must be in the future.
Source code in pydantic/types.py
2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 |
|
EncoderProtocol ¶
Bases: Protocol
Protocol for encoding and decoding data to and from bytes.
Source code in pydantic/types.py
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 |
|
decode
classmethod
¶
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
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 |
|
encode
classmethod
¶
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
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 |
|
get_json_format
classmethod
¶
get_json_format() -> str
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
2313 2314 2315 2316 2317 2318 2319 2320 |
|
Base64Encoder ¶
Bases: EncoderProtocol
Standard (non-URL-safe) Base64 encoder.
Source code in pydantic/types.py
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 |
|
decode
classmethod
¶
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
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 |
|
encode
classmethod
¶
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
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 |
|
get_json_format
classmethod
¶
get_json_format() -> Literal['base64']
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
2353 2354 2355 2356 2357 2358 2359 2360 |
|
Base64UrlEncoder ¶
Bases: EncoderProtocol
URL-safe Base64 encoder.
Source code in pydantic/types.py
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 |
|
decode
classmethod
¶
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
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 |
|
encode
classmethod
¶
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
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 |
|
get_json_format
classmethod
¶
get_json_format() -> Literal['base64url']
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
2393 2394 2395 2396 2397 2398 2399 2400 |
|
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]
'''
Source code in pydantic/types.py
2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 |
|
decode ¶
decode(data: bytes, _: ValidationInfo) -> bytes
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
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 |
|
encode ¶
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
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 |
|
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]
'''
Source code in pydantic/types.py
2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 |
|
decode_str ¶
decode_str(data: bytes, _: ValidationInfo) -> str
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
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 |
|
encode_str ¶
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
2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 |
|
GetPydanticSchema
dataclass
¶
Usage Documentation
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'
Source code in pydantic/types.py
2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 |
|
Tag
dataclass
¶
Provides a way to specify the expected tag to use for a case of a (callable) discriminated union.
Also provides a way to label a union case in error messages.
When using a callable Discriminator
, attach a Tag
to each case in the Union
to specify the tag that
should be used to identify that case. For example, in the below example, the Tag
is used to specify that
if get_discriminator_value
returns 'apple'
, the input should be validated as an ApplePie
, and if it
returns 'pumpkin'
, the input should be validated as a PumpkinPie
.
The primary role of the Tag
here is to map the return value from the callable Discriminator
function to
the appropriate member of the Union
in question.
from typing import Any, Union
from typing_extensions import Annotated, Literal
from pydantic import BaseModel, Discriminator, Tag
class Pie(BaseModel):
time_to_cook: int
num_ingredients: int
class ApplePie(Pie):
fruit: Literal['apple'] = 'apple'
class PumpkinPie(Pie):
filling: Literal['pumpkin'] = 'pumpkin'
def get_discriminator_value(v: Any) -> str:
if isinstance(v, dict):
return v.get('fruit', v.get('filling'))
return getattr(v, 'fruit', getattr(v, 'filling', None))
class ThanksgivingDinner(BaseModel):
dessert: Annotated[
Union[
Annotated[ApplePie, Tag('apple')],
Annotated[PumpkinPie, Tag('pumpkin')],
],
Discriminator(get_discriminator_value),
]
apple_variation = ThanksgivingDinner.model_validate(
{'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
)
print(repr(apple_variation))
'''
ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
'''
pumpkin_variation = ThanksgivingDinner.model_validate(
{
'dessert': {
'filling': 'pumpkin',
'time_to_cook': 40,
'num_ingredients': 6,
}
}
)
print(repr(pumpkin_variation))
'''
ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
'''
Note
You must specify a Tag
for every case in a Tag
that is associated with a
callable Discriminator
. Failing to do so will result in a PydanticUserError
with code
callable-discriminator-no-tag
.
See the Discriminated Unions concepts docs for more details on how to use Tag
s.
Source code in pydantic/types.py
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 |
|
Discriminator
dataclass
¶
Usage Documentation
Provides a way to use a custom callable as the way to extract the value of a union discriminator.
This allows you to get validation behavior like you'd get from Field(discriminator=<field_name>)
,
but without needing to have a single shared field across all the union choices. This also makes it
possible to handle unions of models and primitive types with discriminated-union-style validation errors.
Finally, this allows you to use a custom callable as the way to identify which member of a union a value
belongs to, while still seeing all the performance benefits of a discriminated union.
Consider this example, which is much more performant with the use of Discriminator
and thus a TaggedUnion
than it would be as a normal Union
.
from typing import Any, Union
from typing_extensions import Annotated, Literal
from pydantic import BaseModel, Discriminator, Tag
class Pie(BaseModel):
time_to_cook: int
num_ingredients: int
class ApplePie(Pie):
fruit: Literal['apple'] = 'apple'
class PumpkinPie(Pie):
filling: Literal['pumpkin'] = 'pumpkin'
def get_discriminator_value(v: Any) -> str:
if isinstance(v, dict):
return v.get('fruit', v.get('filling'))
return getattr(v, 'fruit', getattr(v, 'filling', None))
class ThanksgivingDinner(BaseModel):
dessert: Annotated[
Union[
Annotated[ApplePie, Tag('apple')],
Annotated[PumpkinPie, Tag('pumpkin')],
],
Discriminator(get_discriminator_value),
]
apple_variation = ThanksgivingDinner.model_validate(
{'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
)
print(repr(apple_variation))
'''
ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
'''
pumpkin_variation = ThanksgivingDinner.model_validate(
{
'dessert': {
'filling': 'pumpkin',
'time_to_cook': 40,
'num_ingredients': 6,
}
}
)
print(repr(pumpkin_variation))
'''
ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
'''
See the Discriminated Unions concepts docs for more details on how to use Discriminator
s.
Source code in pydantic/types.py
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 |
|
discriminator
instance-attribute
¶
The callable or field name for discriminating the type in a tagged union.
A Callable
discriminator must extract the value of the discriminator from the input.
A str
discriminator must be the name of a field to discriminate against.
custom_error_type
class-attribute
instance-attribute
¶
custom_error_type: str | None = None
Type to use in custom errors replacing the standard discriminated union validation errors.
FailFast
dataclass
¶
Bases: PydanticMetadata
, BaseMetadata
A FailFast
annotation can be used to specify that validation should stop at the first error.
This can be useful when you want to validate a large amount of data and you only need to know if it's valid or not.
You might want to enable this setting if you want to validate your data faster (basically, if you use this, validation will be more performant with the caveat that you get less information).
from typing import List
from typing_extensions import Annotated
from pydantic import BaseModel, FailFast, ValidationError
class Model(BaseModel):
x: Annotated[List[int], FailFast()]
# This will raise a single error for the first invalid value and stop validation
try:
obj = Model(x=[1, 2, 'a', 4, 5, 'b', 7, 8, 9, 'c'])
except ValidationError as e:
print(e)
'''
1 validation error for Model
x.2
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
'''
Source code in pydantic/types.py
3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 |
|
conint ¶
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]
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
|
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
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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
|
confloat ¶
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]
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 |
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
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 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
|
conbytes ¶
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.
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
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 |
|
constr ¶
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 | Pattern[str] | None = None
) -> type[str]
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 typing_extensions import Annotated
from pydantic import BaseModel, 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)
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 | 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
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 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 |
|
conset ¶
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.
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
832 833 834 835 836 837 838 839 840 841 842 843 844 845 |
|
confrozenset ¶
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.
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
848 849 850 851 852 853 854 855 856 857 858 859 860 861 |
|
conlist ¶
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.
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. Warning The |
None
|
Returns:
Type | Description |
---|---|
type[list[AnyItemType]]
|
The wrapped list type. |
Source code in pydantic/types.py
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 |
|
condecimal ¶
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]
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
|
gt |
int | Decimal | None
|
The value must be greater than this. Defaults to |
None
|
ge |
int | Decimal | None
|
The value must be greater than or equal to this. Defaults to |
None
|
lt |
int | Decimal | None
|
The value must be less than this. Defaults to |
None
|
le |
int | Decimal | None
|
The value must be less than or equal to this. Defaults to |
None
|
multiple_of |
int | Decimal | None
|
The value must be a multiple of this. Defaults to |
None
|
max_digits |
int | None
|
The maximum number of digits. Defaults to |
None
|
decimal_places |
int | None
|
The number of decimal places. Defaults to |
None
|
allow_inf_nan |
bool | None
|
Whether to allow infinity and NaN. Defaults to |
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
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 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 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 |
|
condate ¶
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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
strict |
bool | None
|
Whether to validate the date value in strict mode. Defaults to |
None
|
gt |
date | None
|
The value must be greater than this. Defaults to |
None
|
ge |
date | None
|
The value must be greater than or equal to this. Defaults to |
None
|
lt |
date | None
|
The value must be less than this. Defaults to |
None
|
le |
date | None
|
The value must be less than or equal to this. Defaults to |
None
|
Returns:
Type | Description |
---|---|
type[date]
|
A date type with the specified constraints. |
Source code in pydantic/types.py
2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 |
|