Strict Types
Strict types enable you to prevent coercion from compatible types.
Strict types¶
Pydantic provides the following strict types:
These types will only pass validation when the validated value is of the respective type or is a subtype of that type.
Constrained types¶
This behavior is also exposed via the strict field of the constrained types and can be combined with a multitude of complex validation rules. See the individual type signatures for supported arguments.
The following caveats apply:
StrictBytes(and thestrictoption ofconbytes()) will accept bothbytes, andbytearraytypes.StrictInt(and thestrictoption ofconint()) will not acceptbooltypes, even thoughboolis a subclass ofintin Python. Other subclasses will work.StrictFloat(and thestrictoption ofconfloat()) will not acceptint.
Besides the above, you can also have a FiniteFloat type that will only accept finite values (i.e. not inf, -inf or nan).
from pydantic import BaseModel, FiniteFloat, StrictInt, ValidationError
class StrictIntModel(BaseModel):
strict_int: StrictInt
class Model(BaseModel):
finite: FiniteFloat
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]
"""
m = Model(finite=1.0)
print(m)
#> finite=1.0
You can also use pydantic.StringConstraints in Annotated instead of constr for better compatibility with type checkers and more flexibility in nesting within other types:
from typing_extensions import Annotated
from pydantic import BaseModel, StringConstraints, ValidationError
FirstName = Annotated[
str,
StringConstraints(to_upper=True, pattern=r'[A-Z0-9]{3}-[A-Z0-9]{3}'),
]
class Model(BaseModel):
license_plate: FirstName
try:
Model(license_plate='XYZ')
except ValidationError as e:
print(e)
"""
1 validation error for Model
license_plate
String should match pattern '[A-Z0-9]{3}-[A-Z0-9]{3}' [type=string_pattern_mismatch, input_value='XYZ', input_type=str]
"""
m = Model(license_plate='ABC-123')
print(m)
#> license_plate='ABC-123'