Annotations

Introduction

Python type hints for annotations, generics, protocols and static checks.

Annotate a function

x: int = 1
name: str = "Ada"
count: int = 3

def greet(who: str = name) -> str:
    return f"Hi {who}"

def done() -> None:
    pass

done()
print(greet(), count, x)

See: Function annotations

Optional and unions

from typing import Optional

def double(x: int | None) -> int:
    if x is None:
        return 0
    return x * 2

x: int = 1
maybe: str | None = "hi"
assert maybe is not None

# legacy
legacy: Optional[int] = 1

See: Optional

Run a checker

Mypy

mypy app.py
mypy --strict src/
mypy -p package
python -m mypy app.py

Pyright

pyright app.py
pyright --warnings

Both commands fail when they find errors.

See: mypy command line

Structures

Built-in generics

from collections.abc import Iterable, Mapping, Sequence

nums: list[int] = [1, 2, 3]
scores: dict[str, int] = {"a": 1}
names: set[str] = {"a"}
pair: tuple[int, str] = (1, "a")
rest: tuple[int, ...] = (1, 2)

def first(xs: Sequence[int]) -> int:
    return xs[0]

def walk(data: Mapping[str, int]) -> Iterable[int]:
    return data.values()

print(first(nums), list(walk(scores)), names, pair, rest)

These types accept any matching container, not just list or dict.

See: Generic aliases

TypedDict

from typing import NotRequired, TypedDict

class User(TypedDict):
    name: str
    age: int
    email: NotRequired[str]

u: User = {"name": "Ada", "age": 36}
v: User = {"name": "Bob", "age": 30, "email": "b@x.io"}
print(u["name"], v.get("email"))

Use a dataclass when entries need methods or must be distinct objects.

See: TypedDict

Typed tuples

from typing import NamedTuple

point: tuple[int, int] = (1, 2)
label: tuple[str, int] = ("a", 1)
rest: tuple[int, ...] = (1, 2, 3)

class Pair(NamedTuple):
    left: int
    right: str

print(point, label, rest, Pair(1, "x").right)

A NamedTuple gives each position a name; a plain tuple does not.

See: NamedTuple

Data classes

from dataclasses import dataclass, field
from typing import ClassVar

@dataclass(frozen=True)
class Config:
    name: str
    tags: list[str] = field(default_factory=list[str])
    kind: ClassVar[str] = "app"

c = Config("demo")
print(c.name, c.tags, Config.kind)

ClassVar is shared by every instance; field gives each one a fresh list.

See: dataclasses

Protocols

from typing import Protocol, runtime_checkable

@runtime_checkable
class Named(Protocol):
    name: str

def show(x: Named) -> str:
    return x.name

def check(value: object) -> bool:
    return isinstance(value, Named)

class User:
    name = "Ada"

print(show(User()), check(User()))

Named is a checklist: any object with a name: str fits, even without inheriting. @runtime_checkable adds a runtime isinstance check, but only for names, not their types.

See: Protocol

Generics

Type variables

from typing import TypeVar

T = TypeVar("T")
B = TypeVar("B", bound=int)
N = TypeVar("N", int, float)

def first(xs: list[T]) -> T:
    return xs[0]

def keep(x: B) -> B:
    return x

def same(x: N) -> N:
    return x

print(first([1, 2]), keep(2), same(1.5))

T is a placeholder: the type you pass in is the type you get back. A bound allows subclasses; constraints list the exact choices.

See: TypeVar

Generic classes

from typing import Generic, TypeVar

T = TypeVar("T")

class Box(Generic[T]):
    def __init__(self, value: T) -> None:
        self.value = value

    def get(self) -> T:
        return self.value

ints: Box[int] = Box(1)
text: Box[str] = Box("a")
print(ints.get(), text.get())

Box[int] holds ints; Box[str] holds strings. The checker tracks which is which.

See: Generic

Callbacks

from collections.abc import Callable

def apply(fn: Callable[[int], str], x: int) -> str:
    return fn(x)

def compare(fn: Callable[[int, str], bool]) -> bool:
    return fn(1, "x")

def run(fn: Callable[..., str]) -> str:
    return fn()

print(apply(str, 3), compare(lambda n, s: n > 0))
print(run(lambda: "ok"))

The last item in [...] is the return type; the rest are parameters.

See: Callable

ParamSpec decorators

from collections.abc import Callable
from typing import ParamSpec, TypeVar

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

def log(fn: Callable[P, R]) -> Callable[P, R]:
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        print("call", fn.__name__)
        return fn(*args, **kwargs)
    return wrapper

@log
def add(x: int, y: int) -> int:
    return x + y

print(add(1, 2))

P captures every parameter; R captures only the return type.

See: ParamSpec

Overloads

from typing import Literal, overload

@overload
def parse(s: str, *, json: Literal[True]) -> dict[str, str]: ...
@overload
def parse(s: str, *, json: Literal[False] = False) -> str: ...
def parse(s: str, *, json: bool = False) -> dict[str, str] | str:
    return {"a": "b"} if json else s

print(parse("a"), parse("{}", json=True))

Each @overload line describes one allowed call; the final function handles them all.

See: overload

Precision

Literal values

from typing import Final, Literal

ROOT: Final[str] = "/tmp"
mode: Literal["r", "w"] = "r"

def open_it(path: str, mode: Literal["r", "w"] = "r") -> str:
    return path + mode

def go(cmd: Literal["up", "down"]) -> int:
    return 1 if cmd == "up" else -1

print(ROOT, open_it("x"), go("up"), mode)

Literal limits values to the listed strings; Final prevents reassignment.

See: Literal

Annotated metadata

from typing import Annotated

Age = Annotated[int, "years"]
where: Annotated[str, "path"] = "/tmp"

def birthday(age: Age) -> Age:
    return age + 1

def label(tag: Annotated[str, "title"]) -> str:
    return tag.upper()

print(birthday(36), label("ada"), where)

Tools like FastAPI read the metadata; mypy and pyright ignore it.

See: Annotated

Self

from typing import Self

class Builder:
    def __init__(self) -> None:
        self.parts: list[str] = []

    def add(self, part: str) -> Self:
        self.parts.append(part)
        return self

    def __enter__(self) -> Self:
        return self

    def __exit__(self, *args: object) -> None:
        pass

print(Builder().add("x").parts)

Self means "this exact class", including subclasses, so chains stay typed.

See: Self

Type guards

from typing import TypeGuard

def is_strings(xs: list[object]) -> TypeGuard[list[str]]:
    return all(isinstance(x, str) for x in xs)

def join(xs: list[object]) -> str:
    if is_strings(xs):
        return " ".join(xs)
    return ""

print(join(["a", "b"]))

A type guard is a function whose True result narrows the checked value.

See: TypeGuard

Runtime

Deferred annotations

from annotationlib import Format, get_annotations

class Node:
    def next(self) -> Node | None:
        return None

ref: Node | None = None

def echo(x: "int") -> int:
    return x

print(Node().next(), ref, echo(1))
# None None 1

print(get_annotations(Node.next, format=Format.STRING))
# {'return': 'Node | None'}

Python 3.14 defers hints without a future import.

See: annotationlib

Inspect hints

from typing import get_args, get_origin, get_type_hints

def scale(x: int) -> float:
    return float(x)

print(get_type_hints(scale))
# {'x': <class 'int'>, 'return': <class 'float'>}

print(get_origin(list[int]))
# <class 'list'>

print(get_args(dict[str, int]))
# (<class 'str'>, <class 'int'>)

print(get_args(int | None))
# (<class 'int'>, <class 'NoneType'>)

These helpers read hints at runtime: get_origin strips the outer type, get_args lists its parts.

See: get_type_hints

isinstance limits

def check(x: object) -> bool:
    return isinstance(x, list)

def exact(x: object) -> bool:
    return type(x) is list

def generic(x: object) -> bool:
    return isinstance(x, list[int])  # type: ignore[misc]

xs = [1, 2]
print(check(xs), exact(xs))
# True True

try:
    generic(xs)
except TypeError as e:
    print(type(e).__name__)
# TypeError

isinstance cannot check item types; type(x) is list checks the exact class.

See: isinstance

Cast and ignores

from typing import cast

raw: object = "42"
other: object = 7
text = cast(str, raw)
num = cast(int, other)
bad: int = "x"  # type: ignore[assignment]

print(text.upper(), num + 1, bad)
# 42 8 x

mypy and pyright trust cast without checking that it is true.

See: cast

Configure

Strict mypy

[tool.mypy]
strict = true
files = ["src", "tests"]
python_version = "3.14"
warn_unreachable = true

[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false

This override turns one strict check off for test files.

See: mypy config file

Pyright

{
  "include": ["src"],
  "exclude": ["tests"],
  "typeCheckingMode": "strict",
  "pythonVersion": "3.14",
  "reportMissingTypeStubs": false
}

standard is the default; strict enables the full diagnostic set.

See: Pyright configuration

Type-only imports

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from collections.abc import Iterable

def consume(xs: "Iterable[int]") -> int:
    return sum(xs)

print(consume([1, 2]))
# 3

TYPE_CHECKING is false at runtime, so the import is skipped there and cycles stay out of execution.

See: TYPE_CHECKING

0 Comments for this cheatsheet. Write yours!