typestar

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

  1. A field validator returns the cleaned value or raises.
  2. mode=\u0022after\u0022 runs once the type has been coerced.
  3. A model validator can compare fields against each other.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 5 in Pydantic models, step 3 of 19 in Web services & data access.

← Previous Next →