An integer that must be less than or equal to zero.
frompydanticimportBaseModel,NonPositiveInt,ValidationErrorclassModel(BaseModel):non_positive_int:NonPositiveIntm=Model(non_positive_int=0)print(repr(m))#> Model(non_positive_int=0)try:Model(non_positive_int=1)exceptValidationErrorase: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', } ] '''
frompydanticimportBaseModel,StrictInt,ValidationErrorclassStrictIntModel(BaseModel):strict_int:StrictInttry:StrictIntModel(strict_int=3.14159)exceptValidationErrorase: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] '''
frompydanticimportBaseModel,NonPositiveFloat,ValidationErrorclassModel(BaseModel):non_positive_float:NonPositiveFloatm=Model(non_positive_float=0.0)print(repr(m))#> Model(non_positive_float=0.0)try:Model(non_positive_float=1.0)exceptValidationErrorase: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', } ] '''
frompydanticimportBaseModel,StrictFloat,ValidationErrorclassStrictFloatModel(BaseModel):strict_float:StrictFloattry:StrictFloatModel(strict_float='1.0')exceptValidationErrorase: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] '''
frompathlibimportPathfrompydanticimportBaseModel,FilePath,ValidationErrorclassModel(BaseModel):f:FilePathpath=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')# directoryexceptValidationErrorase: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')exceptValidationErrorase: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] '''
frompathlibimportPathfrompydanticimportBaseModel,DirectoryPath,ValidationErrorclassModel(BaseModel):f:DirectoryPathpath=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')# fileexceptValidationErrorase: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')exceptValidationErrorase: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] '''
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.
frompydanticimportBase64Bytes,BaseModel,ValidationErrorclassModel(BaseModel):base64_bytes:Base64Bytes# Initialize the model with base64 datam=Model(base64_bytes=b'VGhpcyBpcyB0aGUgd2F5')# Access decoded valueprint(m.base64_bytes)#> b'This is the way'# Serialize into the base64 formprint(m.model_dump())#> {'base64_bytes': b'VGhpcyBpcyB0aGUgd2F5'}# Validate base64 datatry:print(Model(base64_bytes=b'undecodable').base64_bytes)exceptValidationErrorase:print(e)''' 1 validation error for Model base64_bytes Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value=b'undecodable', input_type=bytes] '''
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.
frompydanticimportBase64Str,BaseModel,ValidationErrorclassModel(BaseModel):base64_str:Base64Str# Initialize the model with base64 datam=Model(base64_str='VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y')# Access decoded valueprint(m.base64_str)#> These aren't the droids you're looking for# Serialize into the base64 formprint(m.model_dump())#> {'base64_str': 'VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y'}# Validate base64 datatry:print(Model(base64_str='undecodable').base64_str)exceptValidationErrorase:print(e)''' 1 validation error for Model base64_str Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value='undecodable', input_type=str] '''
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 '/').
frompydanticimportBase64UrlBytes,BaseModelclassModel(BaseModel):base64url_bytes:Base64UrlBytes# Initialize the model with base64 datam=Model(base64url_bytes=b'SHc_dHc-TXc==')print(m)#> base64url_bytes=b'Hw?tw>Mw'
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 '/').
frompydanticimportBase64UrlStr,BaseModelclassModel(BaseModel):base64url_str:Base64UrlStr# Initialize the model with base64 datam=Model(base64url_str='SHc_dHc-TXc==')print(m)#> base64url_str='Hw?tw>Mw'
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:
frommathimportcosfrompydanticimportBaseModel,ImportString,ValidationErrorclassImportThings(BaseModel):obj:ImportString# A string value will cause an automatic importmy_cos=ImportThings(obj='math.cos')# You can use the imported function as you would expectcos_of_0=my_cos.obj(0)assertcos_of_0==1# A string whose value cannot be imported will raise an errortry:ImportThings(obj='foo.bar')exceptValidationErrorase: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 wellmy_cos=ImportThings(obj=cos)my_cos_2=ImportThings(obj='math.cos')assertmy_cos==my_cos_2
Serializing an ImportString type to json is also possible.
frompydanticimportBaseModel,ImportStringclassImportThings(BaseModel):obj:ImportString# Create an instancem=ImportThings(obj='math:cos')print(m)#> obj=<built-in function cos>print(m.model_dump_json())#> {"obj":"math.cos"}
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:
fromtypingimportAny,ListfrompydanticimportBaseModel,Json,ValidationErrorclassAnyJsonModel(BaseModel):json_obj:Json[Any]classConstrainedJsonModel(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)exceptValidationErrorase: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]')exceptValidationErrorase: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"]')exceptValidationErrorase: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:
Validate the card number and return a PaymentCardNumber instance.
Source code in pydantic/types.py
1572157315741575
@classmethoddefvalidate(cls,__input_value:str,_:core_schema.ValidationInfo)->PaymentCardNumber:"""Validate the card number and return a `PaymentCardNumber` instance."""returncls(__input_value)
@classmethoddefvalidate_digits(cls,card_number:str)->None:"""Validate that the card number is all digits."""ifnotcard_number.isdigit():raisePydanticCustomError('payment_card_number_digits','Card number is not all digits')
@classmethoddefvalidate_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%2foriinrange(length-1):digit=int(card_number[i])ifi%2==parity:digit*=2ifdigit>9:digit-=9sum_+=digitvalid=sum_%10==0ifnotvalid:raisePydanticCustomError('payment_card_number_luhn','Card number is not luhn valid')returncard_number
@staticmethoddefvalidate_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). """ifcard_number[0]=='4':brand=PaymentCardBrand.visaelif51<=int(card_number[:2])<=55:brand=PaymentCardBrand.mastercardelifcard_number[:2]in{'34','37'}:brand=PaymentCardBrand.amexelse:brand=PaymentCardBrand.otherrequired_length:None|int|str=NoneifbrandinPaymentCardBrand.mastercard:required_length=16valid=len(card_number)==required_lengthelifbrand==PaymentCardBrand.visa:required_length='13, 16 or 19'valid=len(card_number)in{13,16,19}elifbrand==PaymentCardBrand.amex:required_length=15valid=len(card_number)==required_lengthelse:valid=Trueifnotvalid:raisePydanticCustomError('payment_card_number_brand','Length for a {brand} card must be {required_length}',{'brand':brand,'required_length':required_length},)returnbrand
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".
defhuman_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. """ifdecimal:divisor=1000units='B','KB','MB','GB','TB','PB'final_unit='EB'else:divisor=1024units='B','KiB','MiB','GiB','TiB','PiB'final_unit='EiB'num=float(self)forunitinunits:ifabs(num)<divisor:ifunit=='B':returnf'{num:0.0f}{unit}'else:returnf'{num:0.1f}{unit}'num/=divisorreturnf'{num:0.1f}{final_unit}'
defto(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()]exceptKeyError:raisePydanticCustomError('byte_size_unit','Could not interpret byte unit: {unit}',{'unit':unit})returnself/unit_div
@classmethoddefdecode(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:returnbase64.decodebytes(data)exceptValueErrorase:raisePydanticCustomError('base64_decode',"Base64 decoding error: '{error}'",{'error':str(e)})
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
20012002200320042005200620072008200920102011
@classmethoddefencode(cls,value:bytes)->bytes:"""Encode the data from bytes to a base64 encoded bytes. Args: value: The data to encode. Returns: The encoded data. """returnbase64.encodebytes(value)
@classmethoddefget_json_format(cls)->Literal['base64']:"""Get the JSON format for the encoded data. Returns: The JSON format for the encoded data. """return'base64'
@classmethoddefdecode(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:returnbase64.urlsafe_b64decode(data)exceptValueErrorase:raisePydanticCustomError('base64_decode',"Base64 decoding error: '{error}'",{'error':str(e)})
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
20412042204320442045204620472048204920502051
@classmethoddefencode(cls,value:bytes)->bytes:"""Encode the data from bytes to a base64 encoded bytes. Args: value: The data to encode. Returns: The encoded data. """returnbase64.urlsafe_b64encode(value)
@classmethoddefget_json_format(cls)->Literal['base64url']:"""Get the JSON format for the encoded data. Returns: The JSON format for the encoded data. """return'base64url'
A bytes type that is encoded and decoded using the specified encoder.
EncodedBytes needs an encoder that implements EncoderProtocol to operate.
fromtyping_extensionsimportAnnotatedfrompydanticimportBaseModel,EncodedBytes,EncoderProtocol,ValidationErrorclassMyEncoder(EncoderProtocol):@classmethoddefdecode(cls,data:bytes)->bytes:ifdata==b'**undecodable**':raiseValueError('Cannot decode data')returndata[13:]@classmethoddefencode(cls,value:bytes)->bytes:returnb'**encoded**: '+value@classmethoddefget_json_format(cls)->str:return'my-encoder'MyEncodedBytes=Annotated[bytes,EncodedBytes(encoder=MyEncoder)]classModel(BaseModel):my_encoded_bytes:MyEncodedBytes# Initialize the model with encoded datam=Model(my_encoded_bytes=b'**encoded**: some bytes')# Access decoded valueprint(m.my_encoded_bytes)#> b'some bytes'# Serialize into the encoded formprint(m.model_dump())#> {'my_encoded_bytes': b'**encoded**: some bytes'}# Validate encoded datatry:Model(my_encoded_bytes=b'**undecodable**')exceptValidationErrorase: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] '''
defdecode(self,data:bytes,_:core_schema.ValidationInfo)->bytes:"""Decode the data using the specified encoder. Args: data: The data to decode. Returns: The decoded data. """returnself.encoder.decode(data)
defencode(self,value:bytes)->bytes:"""Encode the data using the specified encoder. Args: value: The data to encode. Returns: The encoded data. """returnself.encoder.encode(value)
A str type that is encoded and decoded using the specified encoder.
EncodedStr needs an encoder that implements EncoderProtocol to operate.
fromtyping_extensionsimportAnnotatedfrompydanticimportBaseModel,EncodedStr,EncoderProtocol,ValidationErrorclassMyEncoder(EncoderProtocol):@classmethoddefdecode(cls,data:bytes)->bytes:ifdata==b'**undecodable**':raiseValueError('Cannot decode data')returndata[13:]@classmethoddefencode(cls,value:bytes)->bytes:returnb'**encoded**: '+value@classmethoddefget_json_format(cls)->str:return'my-encoder'MyEncodedStr=Annotated[str,EncodedStr(encoder=MyEncoder)]classModel(BaseModel):my_encoded_str:MyEncodedStr# Initialize the model with encoded datam=Model(my_encoded_str='**encoded**: some str')# Access decoded valueprint(m.my_encoded_str)#> some str# Serialize into the encoded formprint(m.model_dump())#> {'my_encoded_str': '**encoded**: some str'}# Validate encoded datatry:Model(my_encoded_str='**undecodable**')exceptValidationErrorase:print(e)''' 1 validation error for Model my_encoded_str Value error, Cannot decode data [type=value_error, input_value='**undecodable**', input_type=str] '''
defdecode_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. """returndata.decode()
defencode_str(self,value:str)->str:"""Encode the data using the specified encoder. Args: value: The data to encode. Returns: The encoded data. """returnsuper(EncodedStr,self).encode(value=value.encode()).decode()# noqa: UP008
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:
fromtypingimportAnyfromtyping_extensionsimportAnnotatedfrompydanticimportBaseModel,GetPydanticSchemaHandleAsAny=GetPydanticSchema(lambda_s,h:h(Any))classModel(BaseModel):x:Annotated[int,HandleAsAny]# pydantic sees `x: Any`print(repr(Model(x='abc').x))#> 'abc'
defconint(*,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: D212returnAnnotated[int,Strict(strict)ifstrictisnotNoneelseNone,annotated_types.Interval(gt=gt,ge=ge,lt=lt,le=le),annotated_types.MultipleOf(multiple_of)ifmultiple_ofisnotNoneelseNone,]
defconfloat(*,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: D212returnAnnotated[float,Strict(strict)ifstrictisnotNoneelseNone,annotated_types.Interval(gt=gt,ge=ge,lt=lt,le=le),annotated_types.MultipleOf(multiple_of)ifmultiple_ofisnotNoneelseNone,AllowInfNan(allow_inf_nan)ifallow_inf_nanisnotNoneelseNone,]
defconbytes(*,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. """returnAnnotated[bytes,Strict(strict)ifstrictisnotNoneelseNone,annotated_types.Len(min_lengthor0,max_length),]
defconstr(*,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: D212returnAnnotated[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,),]
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
782783784785786787788789790791792793794795
defconset(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. """returnAnnotated[Set[item_type],annotated_types.Len(min_lengthor0,max_length)]
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
798799800801802803804805806807808809810811
defconfrozenset(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. """returnAnnotated[FrozenSet[item_type],annotated_types.Len(min_lengthor0,max_length)]
defconlist(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. """ifunique_itemsisnotNone:raisePydanticUserError(('`unique_items` is removed, use `Set` instead''(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)'),code='removed-kwargs',)returnAnnotated[List[item_type],annotated_types.Len(min_lengthor0,max_length)]
defcondecimal(*,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: D212returnAnnotated[Decimal,Strict(strict)ifstrictisnotNoneelseNone,annotated_types.Interval(gt=gt,ge=ge,lt=lt,le=le),annotated_types.MultipleOf(multiple_of)ifmultiple_ofisnotNoneelseNone,_fields.PydanticGeneralMetadata(max_digits=max_digits,decimal_places=decimal_places),AllowInfNan(allow_inf_nan)ifallow_inf_nanisnotNoneelseNone,]
defcondate(*,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. """returnAnnotated[date,Strict(strict)ifstrictisnotNoneelseNone,annotated_types.Interval(gt=gt,ge=ge,lt=lt,le=le),]