Type Hints

Static typing in Python — annotations, mypy and pyright, collections and unions, Optional, generics with TypeVar and the 3.12 syntax, Protocols, TypedDict, Literal, Callable, overloads, and runtime validation with Pydantic.

Intermediate 2 min readLesson 9 of 10

Python is dynamically typed, but since 3.5 it supports optional type hints. They don't change how code runs — the interpreter ignores them (apart from storing them) — but type checkers (mypy, pyright/Pylance, pyrefly, ty) analyse them to catch bugs before runtime, and editors use them for autocomplete and refactoring. Libraries like FastAPI and Pydantic read them at runtime to validate data.

Basics

Python
name: str = "Ada"
age: int = 36
scores: list[int] = [90, 85]                 # built-in generics (3.9+)
lookup: dict[str, float] = {}
point: tuple[float, float] = (1.0, 2.0)
values: tuple[int, ...] = (1, 2, 3)          # variable length

def greet(name: str, times: int = 1) -> str:
    return ", ".join([f"Hi {name}"] * times)

def log(msg: str) -> None: ...

Unions and Optional

Python
def parse(value: str | bytes) -> int: ...          # union (3.10+ syntax; older: Union[str, bytes])

def find_user(id: int) -> User | None:             # Optional[User]
    ...

user = find_user(1)
user.name            # ✗ checker: "name" is not an attribute of None
if user is not None:
    user.name        # ✓ narrowed to User

Checkers narrow types after isinstance, is None, truthiness and equality checks — just like TypeScript (TypeScript basics).

Any, object and cast

  • Any switches checking off for that value — the escape hatch. Use sparingly.
  • object accepts anything but lets you do almost nothing without narrowing — the safe "unknown".
  • typing.cast(T, value) tells the checker "trust me" (no runtime effect).

Literal, Final and enums

Python
from typing import Literal, Final

Mode = Literal["r", "w", "a"]
def open_file(path: str, mode: Mode = "r") -> None: ...
open_file("x.txt", "rw")      # ✗ not a valid literal

MAX_RETRIES: Final = 3        # can't be reassigned

Callables

Python
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence

def apply(fn: Callable[[int, int], int], a: int, b: int) -> int:
    return fn(a, b)

def total(items: Iterable[float]) -> float:      # accept the most general type you can
    return sum(items)

def first_word(words: Sequence[str]) -> str:     # needs indexing → Sequence
    return words[0]

Accept abstract types (Iterable, Sequence, Mapping) in parameters; return concrete types (list, dict).

Generics

Python
# Python 3.12+ syntax
def first[T](items: Sequence[T]) -> T:
    return items[0]

class Stack[T]:
    def __init__(self) -> None:
        self._items: list[T] = []
    def push(self, item: T) -> None:
        self._items.append(item)
    def pop(self) -> T:
        return self._items.pop()

s = Stack[int]()
s.push("x")          # ✗ expected int

# Bounded and constrained type variables
def longest[T: Sized](a: T, b: T) -> T: ...                 # T must be Sized
def concat[S: (str, bytes)](a: S, b: S) -> S: ...           # S is str OR bytes (not mixed)

type Pair[T] = tuple[T, T]                                  # generic type alias (3.12)

Before 3.12: T = TypeVar("T"), class Stack(Generic[T]).

Protocols: static duck typing

A Protocol describes the methods an object needs, without requiring inheritance — structural typing:

Python
from typing import Protocol

class SupportsClose(Protocol):
    def close(self) -> None: ...

class Notifier(Protocol):
    def send(self, to: str, message: str) -> bool: ...

def shutdown(resources: list[SupportsClose]) -> None:
    for r in resources:
        r.close()

shutdown([open("a.txt"), socket.socket()])   # ✓ both have close(), no shared base class needed

Protocols are ideal for dependency injection: business logic declares the interface it needs; adapters satisfy it implicitly (Dependency injection).

Typing dictionaries and records

Python
from typing import TypedDict, NotRequired, NamedTuple
from dataclasses import dataclass

class UserDict(TypedDict):          # for dict-shaped data, e.g. JSON
    id: int
    name: str
    email: NotRequired[str]

def handle(payload: UserDict) -> None:
    payload["name"]                  # str
    payload["nmae"]                  # ✗ typo caught

@dataclass
class User:                          # prefer dataclasses for your own records
    id: int
    name: str

Overloads

When the return type depends on argument types:

Python
from typing import overload

@overload
def load(path: str, binary: Literal[True]) -> bytes: ...
@overload
def load(path: str, binary: Literal[False] = ...) -> str: ...
def load(path: str, binary: bool = False) -> str | bytes:
    mode = "rb" if binary else "r"
    with open(path, mode) as f:
        return f.read()

Other useful constructs

ConstructUse
SelfReturn type of methods returning their own class (fluent APIs)
TypeGuard[T] / TypeIs[T]User-defined narrowing functions
ParamSpecTyping decorators that preserve the wrapped function's signature
Annotated[T, metadata]Attach metadata used by frameworks (FastAPI Query, Pydantic constraints)
NewType("UserId", int)A distinct type at check time with zero runtime cost
Never / assert_neverExhaustiveness checking
@overrideMark overriding methods (3.12)
Python
from typing import ParamSpec, Callable, TypeVar
import functools

P = ParamSpec("P"); R = TypeVar("R")

def logged(fn: Callable[P, R]) -> Callable[P, R]:        # the decorated function keeps its signature
    @functools.wraps(fn)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        print("calling", fn.__name__)
        return fn(*args, **kwargs)
    return wrapper

Running a type checker

Shell
pip install mypy
mypy src/ --strict

# or pyright (also powers VS Code's Pylance)
npx pyright src/
TOML
# pyproject.toml
[tool.mypy]
strict = true
python_version = "3.12"

Adopt gradually: start with function signatures of core modules, enable stricter flags over time, and keep Any out of new code.

Runtime validation: Pydantic

Type hints aren't enforced at runtime. For data from outside — HTTP bodies, config files, queues — validate it. Pydantic turns type hints into validators and parsers:

Python
from pydantic import BaseModel, EmailStr, Field

class SignUp(BaseModel):
    email: EmailStr
    age: int = Field(ge=13, le=130)
    tags: list[str] = []

data = SignUp.model_validate_json('{"email": "ada@example.com", "age": "36"}')
data.age            # 36 (coerced from "36")
SignUp(email="nope", age=5)   # ValidationError with details for each field

FastAPI uses exactly this to validate requests and generate OpenAPI docs from your type hints.

Key takeaways
  • Type hints are ignored at runtime but checked by mypy/pyright and used by editors.
  • Use X | None for optional values; checkers narrow after None and isinstance checks.
  • Accept abstract collection types (Iterable, Sequence, Mapping), return concrete ones.
  • Generics use the 3.12 [T] syntax (or TypeVar); Protocols give structural typing.
  • TypedDict for dict-shaped data, Literal for fixed strings, overload for type-dependent returns.
  • Validate external data at runtime with Pydantic.