Python for AIPython 3.10+ · Pydantic 2.12
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
33 small wins to finish your pathNext lesson

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.

Example
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

Example
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

Example
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

Example
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

Example
result = Triage(category="shipping", priority=3)
print(result.model_dump())

model_dump gives the plain dictionary back, ready for json.dump from lesson 16.

Try it yourself
  • Add a field reply: str | None = None and make a Triage without it.
  • Try priority=4.0, then priority=4.5.
  • Make the error happen inside try and except ValidationError, importing it from pydantic.

This is what real progress feels like.