Code Reference

Typing Hints

Python · Reference cheat sheet

Typing Hints

Python · Reference cheat sheet


📋 Overview

Type hints document and check interfaces with tools like mypy/pyright. They are not enforced at runtime by default. Prefer built-in generics (list[int]) on 3.9+ and | unions on 3.10+.

🔧 Core concepts

FeatureExample
Built-in genericslist[int], dict[str, int]
Unionint | None, str | bytes
OptionalX | None (prefer over Optional)
CallableCallable[[int], str]
TypeAliastype Vector = list[float] (3.12+)
TypeVar / ParamSpecGenerics
ProtocolStructural typing
TypedDictDict shapes
typing.castEscape hatch for checkers
typing.AnyOpt out (use sparingly)

From 3.11+: Self, LiteralString, improved error types. From 3.12+: type statement, PEP 695 generics.

💡 Examples

Functions and collections:

from collections.abc import Iterable, Sequence

def average(xs: Sequence[float]) -> float:
    return sum(xs) / len(xs)

def flatten(rows: Iterable[Iterable[int]]) -> list[int]:
    return [n for row in rows for n in row]

Aliases and TypedDict:

from typing import TypedDict

type UserId = int  # 3.12+; else TypeAlias

class User(TypedDict):
    id: UserId
    name: str
    active: bool

def label(u: User) -> str:
    return f'{u["name"]}#{u["id"]}'

Generics (3.12+):

def first[T](items: Sequence[T]) -> T | None:
    return items[0] if items else None

Protocol:

from typing import Protocol

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

def shutdown(resource: Closable) -> None:
    resource.close()

⚠️ Pitfalls

  • Hints are ignored at runtime unless you validate (pydantic, beartype, etc.).
  • Use collections.abc for Iterable/Mapping/Sequence, not concrete lists only.
  • list is invariant — list[int] is not a list[float | int] for checkers.
  • Avoid Any sprawl; prefer object or precise unions.
  • Forward refs: quote names or from __future__ import annotations.

On this page