Pydantic models: data that checks itself
Type hints describe, and nothing checks them. Pydantic is a package that reads the same hints and checks every value against them when an object is made.
from pydantic import BaseModel
class Triage(BaseModel):
category: str
priority: int
result = Triage(category="billing", priority=4)
print(result)
print(result.priority + 1)A Pydantic model looks like the dataclass from lesson 21, except it inherits from BaseModel instead of using a decorator. Fields are created by name.
It converts when it safely can
result = Triage(category="billing", priority="4")
print(result.priority, type(result.priority))"4" became the int 4. Pydantic converts text that clearly is a number, because data from files and models so often arrives as text.
And refuses when it cannot
Triage(category="billing", priority="high")A ValidationError names the model, the field, what was wrong and the value that was given. Compare lesson 21, where the same mistake was stored silently.
Allowed values and limits
from typing import Literal
from pydantic import BaseModel, Field
class Triage(BaseModel):
category: Literal["billing", "shipping", "other"]
priority: int = Field(ge=1, le=5)
print(Triage(category="shipping", priority=3))
Triage(category="sales", priority=9)Literal[...] allows only the listed values. Field(ge=1, le=5) means greater than or equal to 1 and less than or equal to 5. One bad object gives one error listing every field that failed, not just the first.
Back to a dictionary
result = Triage(category="shipping", priority=3)
print(result.model_dump())model_dump gives the plain dictionary back, ready for json.dump from lesson 16.
- Add a field
reply: str | None = Noneand make a Triage without it. - Try
priority=4.0, thenpriority=4.5. - Make the error happen inside
tryandexcept ValidationError, importing it frompydantic.
This is what real progress feels like.