Pydantic models in Python
A model validates and coerces on construction, from a class of annotations.
from pydantic import BaseModel, ValidationError
class Run(BaseModel):
lang: str
tpm: float
stars: int = 1
run = Run(lang="python", tpm="104.5", stars=3)
print(run.tpm, type(run.tpm).__name__)
print(run.model_dump())
print(run.model_dump_json())
try:
Run(lang="rust", tpm="fast")
except ValidationError as exc:
print(exc.error_count(), exc.errors()[0]["loc"], exc.errors()[0]["type"])
How it works
- Types are enforced: a numeric string becomes an int.
model_dumpandmodel_dump_jsonserialize it back.- A bad value raises ValidationError with the field named.
Keywords and builtins used here
Runasclassexceptfloatintprintstrtrytype
The run, in numbers
- Lines
- 18
- Characters to type
- 388
- Tokens
- 131
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 75 seconds.
Step 1 of 5 in Pydantic models, step 1 of 19 in Web services & data access.