Type Hints

Miss your compiler? Good news — Python can have compile-time safety too. Optional, gradual, and free.

▶ Watch this reel

What you'll learn

  1. Basic hints
  2. Optional & Union
  3. Generics & TypedDict
  4. mypy / pyright

Remember this

Basics

Optional & Union

Generics & TypedDict

def first[T](items: list[T]) -> T:   # 3.12+ (TypeVar before 3.12)
    return items[0]

class ApiResponse(TypedDict):
    model: str
    tokens: int

mypy / pyright

Code: Type hints that earn their keep

from typing import TypedDict, Optional

# --- basics ---------------------------------------------------
def estimate_cost(model: str, tokens: int) -> float:
    prices: dict[str, float] = {"gpt-4o": 2.50, "sonnet": 3.00}
    return tokens / 1_000_000 * prices.get(model, 1.00)

# --- Optional: None must be declared ---------------------------
def find_model(name: str) -> Optional[str]:
    return name if name.startswith("gpt") else None

m = find_model("gpt-4o")
if m is not None:                 # narrowing — mypy verifies this guard
    print(m.upper())

# --- TypedDict: schemas for dict-shaped data -------------------
class ChatMessage(TypedDict):
    role: str
    content: str

class ApiResponse(TypedDict):
    model: str
    message: ChatMessage
    tokens: int

payload: ApiResponse = {
    "model": "gpt-4o",
    "message": {"role": "assistant", "content": "hi"},
    "tokens": 12,
}

# --- check -----------------------------------------------------
# $ pip install mypy
# $ mypy --ignore-missing-imports src/
# CI: mypy src/ && pytest          # types gate + tests gate