Lesson 31 of 52Types in depth
Typing Patterns for Real Code
Type the hard parts of real Python: overloads, decorators with ParamSpec, narrowing with TypeIs, exhaustive matches, TypedDict, NewType and 3.14 annotations.
Your team turns on mypy --strict and the easy parts go green in a day. Then you hit the hard ones. A decorator makes every route handler return Any. A config getter returns str | None even when you passed a default. A webhook payload is a dict of five possible shapes. Someone passes an order id where a user id was expected, and both are int. This lesson covers the patterns that solve those problems, the escape hatches for when they cannot, and how teams roll a checker out across a large codebase without stopping work.
@overload: when the return type depends on the arguments
A settings getter returns None when the key is missing, unless you pass a default. One signature cannot say that, so every caller ends up with str | None and an unnecessary None check. @overload lets you list the signatures the checker should see:
from typing import overload
class Settings:
def __init__(self, data: dict[str, str]) -> None:
self._data = data
@overload
def get(self, key: str) -> str | None: ...
@overload
def get(self, key: str, default: str) -> str: ...
def get(self, key: str, default: str | None = None) -> str | None:
return self._data.get(key, default)
s = Settings({"region": "eu"})
s.get("region") # str | None
s.get("region", "us") # strThe ... stubs are for the checker only. The last, undecorated definition is the one that runs, and callers never see its signature. Checkers try overloads top to bottom and pick the first match, so put the most specific ones first. You will see this pattern throughout the standard library stubs: open() returns a text file or a binary file depending on the mode literal, and dict.get is typed exactly like the example above.
Do not reach for overloads when a type variable will do. def first[T](xs: list[T]) -> T is one signature. Overloads are for when the relationship between inputs and outputs changes, not just the type.
Typing decorators with ParamSpec
The Decorators lesson showed how to write a decorator. Here is how to keep its type. The naive version throws everything away:
from collections.abc import Callable
from typing import Any
def loose(fn: Callable[..., Any]) -> Callable[..., Any]:
return fn
@loose
def charge(user_id: int) -> bool: ...
charge("x", 1, 2) # no error at all
charge(1) # type is AnyCallable[..., Any] means "some callable with any arguments, returning anything". After decoration the checker knows nothing about charge. Every route, task or handler wrapped by such a decorator is effectively untyped.
A ParamSpec captures the whole parameter list of a function, names, defaults and keyword-only markers included. In PEP 695 syntax you write it with two stars:
Press Run (⌘ Enter) to see what happens.Both mypy and pyright now report the decorated charge as (user_id: int, amount_pence: int, *, currency: str = "GBP") -> bool, and charge(1, "100") is an error. P.args and P.kwargs must be used together, exactly as *args: P.args, **kwargs: P.kwargs.
When a decorator injects an argument, such as a database session, use Concatenate to say "the wrapped function takes a Db first, then whatever else":
from collections.abc import Callable
from typing import Concatenate
def with_db[**P, R](fn: Callable[Concatenate[Db, P], R]) -> Callable[P, R]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
return fn(open_db(), *args, **kwargs)
return wrapper
@with_db
def count_orders(db: Db, user_id: int) -> int: ...
count_orders(5) # checker sees (user_id: int) -> intThis is the same technique frameworks use so that typed route handlers, Celery tasks and retry decorators keep their signatures.
def retry(fn: Callable[..., Any]) -> Callable[..., Any]. What happens to type checking of calls to a decorated function?Narrowing beyond isinstance
Narrowing (from Type Hints) is how a checker learns a more precise type inside a branch. Beyond is None and isinstance, checkers narrow on:
- Literal comparisons:
if mode == "r":narrowsLiteral["r", "w"]. - Discriminated unions: a shared literal field that tells the shapes apart. This works for dataclasses and for
TypedDict, which is how you type webhook payloads.
from typing import Literal, TypedDict
class ClickEvent(TypedDict):
type: Literal["click"]
x: int
class KeyEvent(TypedDict):
type: Literal["key"]
key: str
def handle(e: ClickEvent | KeyEvent) -> None:
if e["type"] == "click":
print(e["x"]) # e is ClickEvent
else:
print(e["key"]) # e is KeyEventWhen the check is too complex for the checker to follow, you write a user-defined type guard: a function returning bool whose return annotation tells the checker what True means. There are two kinds, and the difference is a classic interview question.
TypeIs[T](Python 3.13) narrows in both branches. If it returnsTrue, the value isT. IfFalse, the checker removesTfrom the union. Use it by default.TypeGuard[T](3.10) narrows only theTruebranch, and theelsebranch keeps the original type. It also allowsTto be unrelated to the input type, for example narrowinglist[object]tolist[str], whichTypeIsdoes not allow becauselistis invariant.
from typing import TypeGuard, TypeIs
def is_int(x: int | str) -> TypeIs[int]:
return isinstance(x, int)
def is_int_guard(x: int | str) -> TypeGuard[int]:
return isinstance(x, int)
def use(v: int | str) -> None:
if is_int(v):
... # int
else:
... # str (TypeIs removed int)
if is_int_guard(v):
... # int
else:
... # int | str (TypeGuard says nothing here)Checkers trust your guard completely. If the function body is wrong, the types are wrong too, so keep guards small and test them.
Exhaustiveness with Never and assert_never
Never is the type with no values. If the checker narrows a variable down to Never, that code is unreachable. assert_never(x) is a function that only accepts Never, so calling it in the final branch turns "I forgot a case" into a type error:
Press Run (⌘ Enter) to see what happens.A teammate adds Voucher to the Payment alias. Nothing else changes yet.
At runtime, assert_never raises AssertionError if it is ever reached, so a bad value from untyped code fails loudly instead of returning None. The same works with if/elif chains and with enums.
TypedDict in depth
Type Hints introduced TypedDict for dicts with known keys. Real payloads have optional and read-only keys too.
from typing import NotRequired, ReadOnly, Required, TypedDict, Unpack
class User(TypedDict):
id: ReadOnly[int] # 3.13: cannot be assigned after creation
name: str
nickname: NotRequired[str] # may be missing
class Movie(TypedDict, total=False): # every key optional...
title: Required[str] # ...except this one
class CreateUserArgs(TypedDict):
email: str
admin: NotRequired[bool]
def create_user(**kwargs: Unpack[CreateUserArgs]) -> None: ...
create_user(email="a@example.com")
create_user(email="a@example.com", admn=True) # error: did you mean "admin"?total=Falsemakes every key optional;RequiredandNotRequiredoverride per key. PreferNotRequiredon a normal class, it reads better.- Optional keys need
.get(). pyright reportsu["nickname"]as an error because the key may be missing; mypy does not, so on mypy codebases this bug slips through review. ReadOnlymakes a key immutable for the checker. It also loosens assignability, like a property in a protocol: a function taking a TypedDict withn: ReadOnly[float]accepts one whosenisint, which a writablen: floatwould reject.Unpack[TD]types**kwargsprecisely, which is how wrapper functions forward options without a giant signature.- A
TypedDictnormally allows extra keys when it is passed around, since a dict with more keys is still compatible. Python 3.15 adds closed TypedDicts andextra_items=(PEP 728) to say "no other keys" or "other keys must be this type". Check your checker's docs before relying on it.
A TypedDict is a plain dict at runtime with zero validation. For data coming from outside, validate with Pydantic or similar and use TypedDict for shapes you already trust.
The rest of the toolbox
Each of these solves one specific problem:
| Tool | Problem it solves |
|---|---|
Final | A constant must never be reassigned: MAX_RETRIES: Final = 3. |
ClassVar[T] | Mark a class-level attribute (a registry, a counter) so dataclasses and checkers do not treat it as an instance field. |
@final | Forbid subclassing a class or overriding a method. |
@override (3.12) | Declare that a method overrides a parent. A typo like def sav becomes an error instead of a new, never-called method. |
@warnings.deprecated (3.13) | Warn at runtime and in the editor. mypy reports uses once the deprecated error code is enabled. |
NewType | Distinct ID types: UserId and OrderId are both int at runtime but not interchangeable for the checker. |
Annotated[T, meta] | Attach metadata that libraries read at runtime, such as FastAPI's Query(max_length=50) or Pydantic's Field(gt=0). |
LiteralString | Only accept strings written in source code, so f-strings built from user input cannot reach your SQL. |
NewType and Annotated are worth seeing at runtime, because they explain how FastAPI and Pydantic work:
Press Run (⌘ Enter) to see what happens.NewType costs nothing at runtime: UserId(42) returns the plain int 42. Annotated metadata is invisible to the checker (which sees str) and to get_type_hints unless you pass include_extras=True. That one flag is the core of FastAPI's dependency and validation system.
What does this print?
from typing import NewType
UserId = NewType("UserId", int)
uid = UserId(5)
print(type(uid) is int, uid + 1)One honest note on LiteralString: pyright enforces it, but mypy currently treats it as plain str, so on a mypy-only project it documents intent without protecting you. Parameterised queries remain the real defence.
Last resorts: cast and type: ignore
cast(User, row) tells the checker "trust me" and does nothing at runtime. # type: ignore[arg-type] silences one error code on one line. Always include the code in brackets: a bare # type: ignore hides every future error on that line too. --strict turns on warn_unused_ignores, so stale ignores get flagged once the real problem is fixed. In review, treat each cast as a claim that needs a comment explaining why it is true.
Match each problem to the typing tool that solves it.
Annotations at runtime in Python 3.14
Before 3.14, annotations were evaluated when the function or class was defined. A class that referred to itself had to write "Node" in quotes, and many projects added from __future__ import annotations to turn every annotation into a string.
Python 3.14 implements deferred evaluation (PEP 649 and PEP 749). Annotations are stored as code and only evaluated when something asks for them. Forward references just work without quotes, and the __future__ import is now legacy: it still works, but new code does not need it. The new annotationlib module lets tools ask for annotations in different formats:
Press Run (⌘ Enter) to see what happens.Node | None inside Node's own __init__ is fine because nothing evaluates it until get_type_hints runs, by which time Node exists. link refers to a name that never exists: defining the function works, and only reading __annotations__ raises. Format.FORWARDREF gives back real objects where it can and ForwardRef placeholders where it cannot, which is what libraries like Pydantic and dataclasses need.
def f(x: Undefined) -> None: ... where Undefined exists nowhere. What happens?Checkers and rolling them out
mypy is the original checker and still the most common in CI. pyright is faster, powers VS Code's Pylance, and is stricter in several places you saw above (optional TypedDict keys, LiteralString, unsolved type variables). The two disagree on edge cases, so a team picks one as the source of truth for CI. Newer Rust-based checkers have arrived too: Astral's ty (still beta at the time of writing) and Meta's pyrefly. Check their status in the official docs before adopting one.
Rolling --strict out to a large untyped codebase in one go produces thousands of errors and gets turned off again. What works:
- Run the checker in CI on default settings first, fixing real bugs as they appear.
- Make new and core modules strict. With pyright you list paths under
strictin the config. With mypy you setstrict = trueglobally and relax the legacy modules with[[tool.mypy.overrides]](for exampledisallow_untyped_defs = false), then remove overrides one module at a time. - Install stubs for untyped dependencies (
types-requests,types-PyYAML) or ignore missing imports for specific packages only. - If you publish a library, ship a
py.typedmarker file inside the package so checkers use your inline hints.
The Code Quality Tools lesson in the Python Backend course shows the full CI configuration.
- @overload
- Declares several signatures for one function so the return type can depend on the arguments.
- ParamSpec
- A type parameter (
**P) that captures a whole parameter list, used to type decorators. - Concatenate
- Adds parameters in front of a ParamSpec, for decorators that inject or remove an argument.
- TypeIs
- A user-defined type guard (3.13) that narrows the True branch to T and removes T from the else branch.
- assert_never
- Accepts only
Never; placed in the final branch so a forgotten case becomes a type error. - NewType
- A distinct type for the checker that is the plain base type at runtime, used for IDs.
- deferred annotations
- Python 3.14 behaviour: annotations are evaluated only when requested, so forward references need no quotes.