Python Type Hints and Pydantic #4.1
Type checkers use type hints to catch incorrect calls before the program runs. Pydantic validates incoming data at runtime.
When does a type get checked?
What does this code print? The signature of double says it takes an int and returns an int. The input is the string "3".
from pydantic import BaseModel
def double(count: int) -> int:
return count * 2
class Batch(BaseModel):
count: int
print(repr(double("3")))
# prints: '33'
print(double(Batch.model_validate({"count": "3"}).count))
# prints: 6
In the first call, multiplying a string by two repeats it twice. In the second, Pydantic's model_validate parses "3" as an integer before double sees it. The rest of the lesson looks at when a type hint actually gets checked. A static checker reads the hints in the code. Pydantic uses the hints to check incoming values.
| Section | Example | Result |
|---|---|---|
| Static checking | double("3") | '33' at runtime |
| Item types and None | total([2, 3]) | 5 |
| Generic functions | first(["Orbit"]) | 'Orbit' |
| Named dictionary keys | ticket["queue"] | 'billing' |
| Checking a request | batch.model_dump() | {'count': 3} |
| Structured output | route.queue | 'billing' |
How some other languages compare
| Task | TypeScript | Java | Go |
|---|---|---|---|
| Check the code | Type checker reads annotations | Compiler checks types | Compiler checks types |
| Check incoming data | Zod schema | Bean Validation | Validator library reads struct tags |
Static checking with mypy and pyright
Reading def double(count: int) -> int:
| Syntax | Meaning |
|---|---|
count: int | The caller should pass an integer |
-> int | Whenever the function returns, its result should be an integer |
def double(count: int) -> int:
return count * 2
print(double(3))
# prints: 6
print(repr(double("3")))
# prints: '33'
mypy and pyright are static type checkers. They flag the second call because the argument has type str and the parameter expects int. You can run this check before running the program. If you just run the file with Python, the multiplication returns a string.
Item types and None
Reading def total(counts: list[int] | None = None) -> int:
| Syntax | Meaning |
|---|---|
list[int] | A list of integers |
X | None | Either a value of type X or None. Also written Optional[X] |
= None | Use None if the caller omits the argument |
dict[str, int] | A dictionary with string keys and integer values |
from typing import Optional
def total(counts: list[int] | None = None) -> int:
return 0 if counts is None else sum(counts)
def lookup(counts: dict[str, int], name: str) -> Optional[int]:
return counts.get(name)
print(total([2, 3]))
# prints: 5
print(total())
# prints: 0
print(lookup({"Orbit": 5}, "Orbit"))
# prints: 5
print(lookup({}, "Orbit"))
# prints: None
Preserving the return type with TypeVar
Take the first item from a nonempty list. With a list[str], the caller should be able to call .upper() on the result. With a list[int], the same function should return a value the caller can add to another integer.
Reading def first(items: list[T]) -> T:
| Syntax | Meaning |
|---|---|
T = TypeVar("T") | Declare a type variable |
items: list[T] | The item type determines T for this call |
-> T | The result has that same type |
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T:
return items[0]
print(first(["Orbit"]))
# prints: Orbit
print(first([3, 5]) + 1)
# prints: 4
This is a generic function. One implementation lets the checker infer a specific return type at each call.
TypedDict and Literal
When each key in a dictionary has a distinct role, TypedDict describes the type of each entry. Literal narrows a type to specific values. A support ticket, for example, has an integer ID and can go to one of two queues.
| Syntax | Meaning |
|---|---|
class Ticket(TypedDict) | Declare the keys the checker expects |
Literal["billing", "tech"] | Accept only these two strings during type checking |
from typing import Literal, TypedDict
class Ticket(TypedDict):
id: int
queue: Literal["billing", "tech"]
ticket: Ticket = {"id": 42, "queue": "billing"}
print(ticket["queue"])
# prints: billing
print(type(ticket).__name__)
# prints: dict
If the assignment contains the typo "biling", a checker can point straight to it. At runtime, ticket is an ordinary dictionary. For types that describe an object's behavior, see ABC and Protocol in part 3.1.
Checking incoming data with Pydantic
Part 3.1 compares dataclasses and Pydantic. Here a request supplies a batch size as a string. Before using it to split up work, check two things. The value must parse as an integer, and each batch must hold at least one item.
| Syntax | Meaning |
|---|---|
Batch.model_validate(raw) | Read a dictionary and return a Batch if the data is valid |
@field_validator("count") | Attach a check to count. By default it receives the value after Pydantic has parsed it |
batch.model_dump() | Export the model's fields as a dictionary |
from pydantic import BaseModel, ValidationError, field_validator
class Batch(BaseModel):
count: int
@field_validator("count")
@classmethod
def positive(cls, value: int) -> int:
if value < 1:
raise ValueError("count must be positive")
return value
raw = {"count": "3"}
batch = Batch.model_validate(raw)
print(batch.model_dump())
# prints: {'count': 3}
try:
Batch.model_validate({"count": "0"})
except ValidationError as exc:
error = exc.errors()[0]
print(error["loc"], error["msg"])
# prints: ('count',) Value error, count must be positive
With its default settings, Pydantic v2 parses "0" as an integer. The positive method receives zero and raises ValueError. The caller gets a ValidationError. In the first error, loc identifies the field and msg explains why it failed. On success, the validator must return the value to store in the model.
Structured output from an LLM
Orbit uses a large language model (LLM) to route support tickets. Instead of searching a paragraph for a queue name, the application can ask for a single queue field. One Pydantic model describes it for both sides. An API that supports structured output can take a JSON Schema describing the expected JSON, and the application can use the same model to read the reply.
from typing import Literal
from pydantic import BaseModel, ValidationError
class Route(BaseModel):
queue: Literal["billing", "tech"]
schema = Route.model_json_schema()
print(schema["properties"]["queue"]["enum"])
# prints: ['billing', 'tech']
reply = '{"queue": "billing"}'
route = Route.model_validate_json(reply)
print(route.queue)
# prints: billing
try:
Route.model_validate_json('{"queue": "sales"}')
except ValidationError as exc:
print(exc.errors()[0]["msg"])
# prints: Input should be 'billing' or 'tech'
Here reply is a sample JSON string. model_validate_json parses the string and checks the value in one step. A queue outside the two allowed values triggers a validation error. If it picks "billing" for a technical issue, the reply still fits the schema. Judging the classification requires looking at the ticket itself.
Key takeaways
- Run mypy or pyright to find calls with the wrong argument type in the code.
- Use
TypeVarwhen the return type depends on the input type. - Use
TypedDictandLiteralto describe a dictionary's keys and the values they allow. - Use Pydantic where real data enters the application. A
ValidationErroridentifies the field that needs attention.
