Number Types
Pydantic supports the following numeric types from the Python standard library:
int
float
enum.IntEnum
decimal.Decimal
Validation of numeric types¶
int
- Pydantic uses
int(v)
to coerce types to anint
; see Data conversion for details on loss of information during data conversion. float
- similarly,
float(v)
is used to coerce values to floats. enum.IntEnum
- checks that the value is a valid
IntEnum
instance. - subclass of
enum.IntEnum
- checks that the value is a valid member of the integer enum; see Enums and Choices for more details.
decimal.Decimal
- Pydantic attempts to convert the value to a string, then passes the string to
Decimal(v)
.
Constrained types¶
Pydantic provides functions that can be used to constrain numbers:
conint
: Add constraints to anint
type.confloat
: Add constraints to afloat
type.condecimal
: Add constraints to adecimal.Decimal
type.
Those functions accept the following arguments:
gt
(greater than)ge
(greater than or equal to)lt
(less than)le
(less than or equal to)multiple_of
(multiple of)strict
(whether to allow coercion from compatible types)
Some functions accept additional arguments, which you can see in the API reference of each function. For example,
confloat
accepts an allow_inf_nan
, which specifies whether to allow -inf
, inf
, and nan
.
Constrained integers¶
There are also types that can be used to constrain integers:
PositiveInt
: Constrain anint
to be positive.NegativeInt
: Constrain anint
to be negative.NonPositiveInt
: Constrain anint
to be non-positive.NonNegativeInt
: Constrain anint
to be non-negative.
from pydantic import (
BaseModel,
NegativeInt,
NonNegativeInt,
NonPositiveInt,
PositiveInt,
)
class Model(BaseModel):
positive: PositiveInt
negative: NegativeInt
non_positive: NonPositiveInt
non_negative: NonNegativeInt
m = Model(positive=1, negative=-1, non_positive=0, non_negative=0)
print(m)
#> positive=1 negative=-1 non_positive=0 non_negative=0
Constrained floats¶
There are also types that can be used to constrain floats:
PositiveFloat
: Constrain afloat
to be positive.NegativeFloat
: Constrain afloat
to be negative.NonPositiveFloat
: Constrain afloat
to be non-positive.NonNegativeFloat
: Constrain afloat
to be non-negative.
from pydantic import (
BaseModel,
NegativeFloat,
NonNegativeFloat,
NonPositiveFloat,
PositiveFloat,
)
class Model(BaseModel):
positive: PositiveFloat
negative: NegativeFloat
non_positive: NonPositiveFloat
non_negative: NonNegativeFloat
m = Model(positive=1.0, negative=-1.0, non_positive=0.0, non_negative=0.0)
print(m)
#> positive=1.0 negative=-1.0 non_positive=0.0 non_negative=0.0
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
class Model(BaseModel):
finite: FiniteFloat
m = Model(finite=1.0)
print(m)
#> finite=1.0