Advanced Python: static typing (typing, Protocol)

Go beyond int and str in Python: Optional, Union, generics, Protocol, TypedDict, and Literal, a short note on mypy, and 20 exercises with solutions.

Illustration : plateau sombre aux encoches de formes variées et loupe examinant l'ajustement des pièces, image du typage avancé

AI-generated illustration

Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.

Python stays dynamically typed at runtime, but annotations (def f(x: int) -> str) let you run static checks with mypy, Pyright, PyCharm, and similar tools. Beyond int and str, the typing module (and, from 3.9 onward, often the lowercase builtins for collections) gives you Protocol (structural subtyping), generics (TypeVar), TypedDict for structured JSON, Literal for constants, and more.

1. Union and Optional

Optional[X] is the same as X | None (Python 3.10+). Union[A, B] is A | B.

2. Protocol (static duck typing)

from typing import Protocol

class Readable(Protocol):
    def read(self, n: int = -1) -> bytes: ...

def consume(r: Readable) -> None:
    r.read(10)

Any class with a compatible read method satisfies Readable without explicit inheritance.

3. Generics

from typing import TypeVar, Generic

T = TypeVar("T")

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

4. TypedDict and Literal

TypedDict describes a dict with known keys (handy for JSON). Literal["r", "w"] restricts a value to constant choices.

External resources

Exercises (20)

Easy

Exercise 1 — Annotate def add(a: int, b: int) -> int. Easy

Show the solution
def add(a: int, b: int) -> int:
    return a + b

Exercise 2 — Rewrite this with X | None instead of Optional[X] (3.10+). Easy

Show the solution
def f(x: int | None) -> str:
    return str(x)

Exercise 3 — list[int] versus List[int] imported from typing (the older style). Easy

Show the solution
# PEP 585: list[int] is built in from 3.9 onward; List[] is the older style for 3.8.

Exercise 4 — A HasName Protocol with a name: str attribute (a @property or a field). Easy

Show the solution
from typing import Protocol

class HasName(Protocol): @property def name(self) -> str: …

Exercise 5 — Literal[1, 2, 3] for a mode parameter. Easy

Show the solution
from typing import Literal

def set_mode(mode: Literal[1, 2, 3]) -> None: pass

Exercise 6 — A TypedDict with keys id and label. Easy

Show the solution
from typing import TypedDict

class Row(TypedDict): id: int label: str

Exercise 7 — Why does Any effectively turn off checking for an expression? Easy

Show the solution
# Any is compatible with every type; use it sparingly.

Intermediate

Exercise 8 — A generic Stack[T] class with push(self, x: T) -> None and pop(self) -> T. Intermediate

Show the solution
from typing import Generic, TypeVar

T = TypeVar(“T”)

class Stack(Generic[T]): def init(self) -> None: self._d: list[T] = [] def push(self, x: T) -> None: self._d.append(x) def pop(self) -> T: return self._d.pop()

Exercise 9 — A bounded TypeVar: T = TypeVar("T", bound=Readable) (with a Readable Protocol). Intermediate

Show the solution
from typing import Protocol, TypeVar

class Readable(Protocol): def read(self, n: int = -1) -> bytes: …

T = TypeVar(“T”, bound=Readable)

def load(r: T) -> bytes: return r.read()

Exercise 10 — overload for parse, accepting str → int and bytes → int (an illustrative signature). Intermediate

Show the solution
from typing import overload

@overload def parse(x: str) -> int: … @overload def parse(x: bytes) -> int: … def parse(x: str | bytes) -> int: return int(x)

Exercise 11 — Final and ClassVar: what each one is for. Intermediate

Show the solution
# Final: a constant you do not reassign. ClassVar: a class attribute, not an instance attribute.

Exercise 12 — Annotated[int, "positive"]: what it is for (PEP 593). Intermediate

Show the solution
# Metadata for third-party tools; the type stays int for the checker.

Exercise 13 — cast(T, x): when should you use it? Intermediate

Show the solution
# When you know the type better than inference does; document it (it is not a runtime conversion).

Exercise 14 — Required / NotRequired in a TypedDict (fully available in 3.11). Intermediate

Show the solution
# Optional keys typed explicitly in a TypedDict, including total=False and inheritance.

Hard

Exercise 15 — ParamSpec / Concatenate to type a decorator (a sketch). Hard

Show the solution
# Preserve *args and **kwargs across wrappers (PEP 612).

Exercise 16 — TypeGuard for an is_str_list predicate. Hard

Show the solution
from typing import TypeGuard

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

Exercise 17 — The difference between nominal and structural typing. Give a Protocol example. Hard

Show the solution
# Nominal: declared inheritance. Structural: compatible methods and attributes (static duck typing).

Exercise 18 — Why did from __future__ import annotations postpone evaluation of annotations? Hard

Show the solution
# Forward references without quotes; that storage behavior is the default from 3.11 onward.

Exercise 19 — A mypy.ini config with strict = True: the trade-off. Hard

Show the solution
# More useful errors, but a costly migration on large legacy codebases.

Exercise 20 — @runtime_checkable on a Protocol: what it gives you, and the limit. Hard

Show the solution
# isinstance(x, Proto) becomes possible; it only checks that the methods exist, not their signatures.

Next in the track

Packaging and pyproject.toml: make a project installable.

Amazon

Check today’s price on Amazon (Python static typing)

Further reading

Was this page helpful?

Have a question about this guide or need advice? Ask us here

Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.