Types/strict types
Strict types enable you to prevent coercion from compatible 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.
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