Validators in Python
field_validator for one field, model_validator for the whole object.
from pydantic import BaseModel, field_validator, model_validator
class Session(BaseModel):
lang: str
started: int
finished: int
@field_validator("lang")
@classmethod
def lowercase(cls, value: str) -> str:
return value.strip().lower()
@model_validator(mode="after")
def check_order(self):
if self.finished < self.started:
raise ValueError("finished before it started")
return self
print(Session(lang=" PYTHON ", started=1, finished=5).lang)
try:
Session(lang="rust", started=9, finished=2)
except ValueError as exc:
print(str(exc).splitlines()[1].strip())
How it works
- A field validator returns the cleaned value or raises.
mode=\u0022after\u0022runs once the type has been coerced.- A model validator can compare fields against each other.
Keywords and builtins used here
Sessionascheck_orderclassclsdefexceptifintlowercaseprintraisereturnselfstrtry
The run, in numbers
- Lines
- 25
- Characters to type
- 561
- Tokens
- 147
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 84 seconds.
Step 3 of 5 in Pydantic models, step 3 of 19 in Web services & data access.