pydantic==1.9.0
Best way
from pydantic import BaseModel, Field
"""
The first argument of Field is 'default', refers to default value of attribute,
if is '...' it means is 'required', if no value is assigned, it defaults to 'undefined'
"""
class Report(BaseModel):
id: int = Field(..., gt=0) # ... is required, and gt is 'greater than'
name: str = Field(..., min_length=1)
grade: float = Field(0.0, gt=0)
proportion: float = Field(0.0, gt=0)
Another way (I do not recommend it but you will probably see it somewhere else.)
from decimal import Decimal
from pydantic import BaseModel, constr, condecimal, conint
class Report(BaseModel):
id: conint(gt=0)
name: constr(min_length=1)
grade: condecimal(gt=Decimal(0.0)) = 0.0
proportion: condecimal(gt=Decimal(0.0)) = 0.0
Check: https://pydantic-docs.helpmanual.io/usage/types/#constrained-types
Edit: if you use MyPy, or you want to use the same validators, you must create a class that inherits from ConstrainedStr, ConstrainedInt, etc...
from decimal import Decimal
from pydantic import ConstrainedStr, ConstrainedInt, ConstrainedDecimal
class IdValidator(ConstrainedInt):
gt=0
class NameValidator(ConstrainedStr):
min_length=1
class DecimalValidator(ConstrainedDecimal):
gt=Decimal(0.0)
class Report(BaseModel):
id: IdValidator
name: NameValidator
grade: DecimalValidator = None
proportion: DecimalValidator = None