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.
Getting started
Home Assistant
Buying
Go beyond int and str in Python: Optional, Union, generics, Protocol, TypedDict, and Literal, a short note on mypy, and 20 exercises with solutions.


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.
Optional[X] is the same as X | None (Python 3.10+). Union[A, B] is A | B.
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.
from typing import TypeVar, Generic
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, x: T) -> None:
self.x = x
TypedDict describes a dict with known keys (handy for JSON). Literal["r", "w"] restricts a value to constant choices.
Exercise 1 — Annotate def add(a: int, b: int) -> int. Easy
def add(a: int, b: int) -> int:
return a + b
Exercise 2 — Rewrite this with X | None instead of Optional[X] (3.10+). Easy
def f(x: int | None) -> str:
return str(x)
Exercise 3 — list[int] versus List[int] imported from typing (the older style). Easy
# 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
from typing import Protocol
class HasName(Protocol): @property def name(self) -> str: …
Exercise 5 — Literal[1, 2, 3] for a mode parameter. Easy
from typing import Literal
def set_mode(mode: Literal[1, 2, 3]) -> None: pass
Exercise 6 — A TypedDict with keys id and label. Easy
from typing import TypedDict
class Row(TypedDict): id: int label: str
Exercise 7 — Why does Any effectively turn off checking for an expression? Easy
# Any is compatible with every type; use it sparingly.
Exercise 8 — A generic Stack[T] class with push(self, x: T) -> None and pop(self) -> T. Intermediate
from typing import Generic, TypeVarT = 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
from typing import Protocol, TypeVarclass 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
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
# 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
# Metadata for third-party tools; the type stays int for the checker.
Exercise 13 — cast(T, x): when should you use it? Intermediate
# 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
# Optional keys typed explicitly in a TypedDict, including total=False and inheritance.
Exercise 15 — ParamSpec / Concatenate to type a decorator (a sketch). Hard
# Preserve *args and **kwargs across wrappers (PEP 612).
Exercise 16 — TypeGuard for an is_str_list predicate. Hard
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
# Nominal: declared inheritance. Structural: compatible methods and attributes (static duck typing).
Exercise 18 — Why did from __future__ import annotations postpone evaluation of annotations? Hard
# 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
# 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
# isinstance(x, Proto) becomes possible; it only checks that the methods exist, not their signatures.
Packaging and pyproject.toml: make a project installable.
Check today’s price on Amazon (Python static typing)
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).