Pydantic Types
The types module contains custom types used by pydantic.
StrictBool
module-attribute
¶
StrictBool = Annotated[bool, Strict()]
A boolean that must be either True
or False
.
PositiveInt
module-attribute
¶
PositiveInt = Annotated[int, annotated_types.Gt(0)]
An integer that must be greater than zero.
NegativeInt
module-attribute
¶
NegativeInt = Annotated[int, annotated_types.Lt(0)]
An integer that must be less than zero.
NonPositiveInt
module-attribute
¶
NonPositiveInt = Annotated[int, annotated_types.Le(0)]
An integer that must be less than or equal to zero.
NonNegativeInt
module-attribute
¶
NonNegativeInt = Annotated[int, annotated_types.Ge(0)]
An integer that must be greater than or equal to zero.
StrictInt
module-attribute
¶
StrictInt = Annotated[int, Strict()]
An integer that must be validated in strict mode.
PositiveFloat
module-attribute
¶
PositiveFloat = Annotated[float, annotated_types.Gt(0)]
A float that must be greater than zero.
NegativeFloat
module-attribute
¶
NegativeFloat = Annotated[float, annotated_types.Lt(0)]
A float that must be less than zero.
NonPositiveFloat
module-attribute
¶
NonPositiveFloat = Annotated[float, annotated_types.Le(0)]
A float that must be less than or equal to zero.
NonNegativeFloat
module-attribute
¶
NonNegativeFloat = Annotated[float, annotated_types.Ge(0)]
A float that must be greater than or equal to zero.
StrictFloat
module-attribute
¶
StrictFloat = Annotated[float, Strict(True)]
A float that must be validated in strict mode.
FiniteFloat
module-attribute
¶
FiniteFloat = Annotated[float, AllowInfNan(False)]
A float that must be finite (not -inf
, inf
, or nan
).
StrictBytes
module-attribute
¶
StrictBytes = Annotated[bytes, Strict()]
A bytes that must be validated in strict mode.
StrictStr
module-attribute
¶
StrictStr = Annotated[str, Strict()]
A string that must be validated in strict mode.
FilePath
module-attribute
¶
FilePath = Annotated[Path, PathType('file')]
A path that must point to a file.
DirectoryPath
module-attribute
¶
DirectoryPath = Annotated[Path, PathType('dir')]
A path that must point to a directory.
NewPath
module-attribute
¶
NewPath = Annotated[Path, PathType('new')]
A path for a new file or directory that must not already exist.
Strict
dataclass
¶
Bases: _fields.PydanticMetadata
, BaseMetadata
A field metadata class to indicate that a field should be validated in strict mode.
Attributes:
Name | Type | Description |
---|---|---|
strict |
bool
|
Whether to validate the field in strict mode. |
Example
from typing_extensions import Annotated
from pydantic.types import Strict
StrictBool = Annotated[bool, Strict()]
AllowInfNan
dataclass
¶
Bases: _fields.PydanticMetadata
A field metadata class to indicate that a field should allow -inf
, inf
, and nan
.
StringConstraints
dataclass
¶
Bases: annotated_types.GroupedMetadata
Apply constraints to str
types.
Attributes:
Name | Type | Description |
---|---|---|
strip_whitespace |
bool | None
|
Whether to strip whitespace from the string. |
to_upper |
bool | None
|
Whether to convert the string to uppercase. |
to_lower |
bool | None
|
Whether to convert the string to lowercase. |
strict |
bool | None
|
Whether to validate the string in strict mode. |
min_length |
int | None
|
The minimum length of the string. |
max_length |
int | None
|
The maximum length of the string. |
pattern |
str | None
|
A regex pattern that the string must match. |
ImportString ¶
A type that can be used to import a type from a string.
Example
from datetime import date
from typing import Type
from pydantic import BaseModel, ImportString
class Foo(BaseModel):
call_date: ImportString[Type[date]]
foo = Foo(call_date="datetime.date")
assert foo.call_date(2021, 1, 1) == date(2021, 1, 1)
Json ¶
A special type wrapper which loads JSON before parsing.
SecretStr ¶
Bases: _SecretField[str]
A string that is displayed as **********
in reprs and can be used for passwords.
Example
from pydantic import BaseModel, SecretStr
class User(BaseModel):
username: str
password: SecretStr
user = User(username='scolvin', password='password1')
print(user)
#> username='scolvin' password=SecretStr('**********')
print(user.password.get_secret_value())
#> password1
SecretBytes ¶
Bases: _SecretField[bytes]
A bytes that is displayed as **********
in reprs and can be used for passwords.
PaymentCardNumber ¶
PaymentCardNumber(card_number)
Bases: str
Based on: https://en.wikipedia.org/wiki/Payment_card_number.
Source code in pydantic/types.py
834 835 836 837 838 839 840 841 |
|
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
854 855 856 857 |
|
validate_digits
classmethod
¶
validate_digits(card_number)
Validate that the card number is all digits.
Source code in pydantic/types.py
869 870 871 872 873 |
|
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
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 |
|
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
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 |
|
ByteSize ¶
Bases: int
Converts a bytes string with units to the number of bytes.
human_readable ¶
human_readable(decimal=False)
Converts a byte size to a human readable string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
decimal |
bool
|
If True, use decimal units (e.g. 1000 bytes per KB). If False, use binary units (e.g. 1024 bytes per KiB). |
False
|
Returns:
Type | Description |
---|---|
str
|
A human readable string representation of the byte size. |
Source code in pydantic/types.py
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 |
|
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
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 |
|
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
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 |
|
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
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 |
|
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
1225 1226 1227 1228 1229 1230 1231 1232 |
|
Base64Encoder ¶
Bases: EncoderProtocol
Base64 encoder.
decode
classmethod
¶
decode(data)
Decode the data from base64 encoded bytes to original bytes data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data |
bytes
|
The data to decode. |
required |
Returns:
Type | Description |
---|---|
bytes
|
The decoded data. |
Source code in pydantic/types.py
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 |
|
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
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 |
|
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
1265 1266 1267 1268 1269 1270 1271 1272 |
|
EncodedBytes
dataclass
¶
A bytes type that is encoded and decoded using the specified encoder.
decode ¶
decode(data, _)
Decode the data using the specified encoder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data |
bytes
|
The data to decode. |
required |
Returns:
Type | Description |
---|---|
bytes
|
The decoded data. |
Source code in pydantic/types.py
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 |
|
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
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 |
|
EncodedStr ¶
Bases: EncodedBytes
A str type that is encoded and decoded using the specified encoder.
decode_str ¶
decode_str(data, _)
Decode the data using the specified encoder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data |
bytes
|
The data to decode. |
required |
Returns:
Type | Description |
---|---|
str
|
The decoded data. |
Source code in pydantic/types.py
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 |
|
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
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 |
|
GetPydanticSchema
dataclass
¶
A convenience class for creating an annotation that provides pydantic custom type hooks.
This class is intended to eliminate the need to create a custom "marker" which defines the
__get_pydantic_core_schema__
and __get_pydantic_json_schema__
custom hook methods.
For example, to have a field treated by type checkers as int
, but by pydantic as Any
, you can do:
from typing import Any
from typing_extensions import Annotated
from pydantic import BaseModel, GetPydanticSchema
HandleAsAny = GetPydanticSchema(lambda _s, h: h(Any))
class Model(BaseModel):
x: Annotated[int, HandleAsAny] # pydantic sees `x: Any`
print(repr(Model(x='abc').x))
#> 'abc'
conint ¶
conint(
*,
strict=None,
gt=None,
ge=None,
lt=None,
le=None,
multiple_of=None
)
A wrapper around int
that allows for additional constraints.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
strict |
bool | None
|
Whether to validate the integer in strict mode. Defaults to |
None
|
gt |
int | None
|
The value must be greater than this. |
None
|
ge |
int | None
|
The value must be greater than or equal to this. |
None
|
lt |
int | None
|
The value must be less than this. |
None
|
le |
int | None
|
The value must be less than or equal to this. |
None
|
multiple_of |
int | None
|
The value must be a multiple of this. |
None
|
Returns:
Type | Description |
---|---|
type[int]
|
The wrapped integer type. |
Source code in pydantic/types.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
|
confloat ¶
confloat(
*,
strict=None,
gt=None,
ge=None,
lt=None,
le=None,
multiple_of=None,
allow_inf_nan=None
)
A wrapper around float
that allows for additional constraints.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
strict |
bool | None
|
Whether to validate the float in strict mode. |
None
|
gt |
float | None
|
The value must be greater than this. |
None
|
ge |
float | None
|
The value must be greater than or equal to this. |
None
|
lt |
float | None
|
The value must be less than this. |
None
|
le |
float | None
|
The value must be less than or equal to this. |
None
|
multiple_of |
float | None
|
The value must be a multiple of this. |
None
|
allow_inf_nan |
bool | None
|
Whether to allow |
None
|
Returns:
Type | Description |
---|---|
type[float]
|
The wrapped float type. |
Source code in pydantic/types.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
|
conbytes ¶
conbytes(*, min_length=None, max_length=None, strict=None)
A wrapper around bytes
that allows for additional constraints.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
min_length |
int | None
|
The minimum length of the bytes. |
None
|
max_length |
int | None
|
The maximum length of the bytes. |
None
|
strict |
bool | None
|
Whether to validate the bytes in strict mode. |
None
|
Returns:
Type | Description |
---|---|
type[bytes]
|
The wrapped bytes type. |
Source code in pydantic/types.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
|
constr ¶
constr(
*,
strip_whitespace=None,
to_upper=None,
to_lower=None,
strict=None,
min_length=None,
max_length=None,
pattern=None
)
A wrapper around str
that allows for additional constraints.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
strip_whitespace |
bool | None
|
Whether to strip whitespace from the string. |
None
|
to_upper |
bool | None
|
Whether to convert the string to uppercase. |
None
|
to_lower |
bool | None
|
Whether to convert the string to lowercase. |
None
|
strict |
bool | None
|
Whether to validate the string in strict mode. |
None
|
min_length |
int | None
|
The minimum length of the string. |
None
|
max_length |
int | None
|
The maximum length of the string. |
None
|
pattern |
str | None
|
A regex pattern that the string must match. |
None
|
Returns:
Type | Description |
---|---|
type[str]
|
The wrapped string type. |
Source code in pydantic/types.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 |
|
conset ¶
conset(item_type, *, min_length=None, max_length=None)
A wrapper around typing.Set
that allows for additional constraints.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
item_type |
type[HashableItemType]
|
The type of the items in the set. |
required |
min_length |
int | None
|
The minimum length of the set. |
None
|
max_length |
int | None
|
The maximum length of the set. |
None
|
Returns:
Type | Description |
---|---|
type[set[HashableItemType]]
|
The wrapped set type. |
Source code in pydantic/types.py
358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
|
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
374 375 376 377 378 379 380 381 382 383 384 385 386 387 |
|
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
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 |
|
condecimal ¶
condecimal(
*,
strict=None,
gt=None,
ge=None,
lt=None,
le=None,
multiple_of=None,
max_digits=None,
decimal_places=None,
allow_inf_nan=None
)
A wrapper around Decimal that adds validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
strict |
bool | None
|
Whether to validate the value in strict mode. Defaults to |
None
|
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
|
Source code in pydantic/types.py
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 |
|
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
|
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
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 |
|