§ 2.3section 3 of 20·~6 min
Type hints
Type hints say what type a variable, parameter or return value should be:
def search(books: list[Book], query: str) -> list[Book]: ...
ages: dict[str, int] = {"Asha": 22}
point: tuple[float, float] = (12.9, 77.5)
maybe_name: str | None = None # "a str, or None" (older code writes Optional[str])
Python does not enforce hints at runtime. search(42, 99) still runs, and probably crashes somewhere inside. So why bother?
- Your editor uses them for autocomplete and underlines mistakes before you run anything.
- Type checkers like
mypyorpyrightcheck a whole codebase for mismatches. - Libraries read them. Pydantic validates data from them, FastAPI builds API docs from them, and in Week 13 your function signatures become the JSON schema the LLM sees when it calls your tools.
The typing toolbox you'll meet in AI code
from typing import Literal, TypedDict, Any, Callable
Category = Literal["food", "travel", "rent", "other"] # only these exact strings are allowed
def add(amount: float, category: Category) -> None: ...
class AgentState(TypedDict): # a dict with known keys and value types
messages: list[str]
attempts: int
state: AgentState = {"messages": [], "attempts": 0}
def apply(fn: Callable[[int], int], x: int) -> int: # a function taking int and returning int
return fn(x)
payload: dict[str, Any] = {"model": "x", "temperature": 0.2} # Any = "could be anything"
Literalshows up in LLM tool definitions ("status must be one of these").TypedDictis exactly how LangGraph defines graph state in Week 15. Look out for it.- Don't overuse
Any, because it switches type checking off.
Try it
Add full type hints to every function in your Week 1 expense tracker. Then install Pylance in VS Code (it comes with the Python extension), set Type Checking Mode to basic, and fix anything it underlines.