Part 15 / Stage 3
Advanced typing and errors
Goal: Describe shapes instead of base classes with
Protocol, write your own generic functions and classes, describe dicts with fixed and optional keys withTypedDict, match deeply nested data withmatch, and report many failures at once withExceptionGroup/except*. Time: ~1 hour
What you will learn
Protocol: a type that describes a shape (methods/attributes), not a base class@runtime_checkable: lettingisinstance()check aProtocol- Generics you write yourself, with the modern syntax:
def f[T](),class Box[T] TypedDictin depth:NotRequired,Required, and oneTypedDictinheriting anothermatchgoing deeper: class patterns, sequence patterns, mapping patterns, nested patternsExceptionGroupandexcept*: raising and handling several exceptions from one job- Putting it together: routing webhook events with
match
About "Python 3.14": this part uses features from several recent versions:
Protocol(3.8), structuralmatch(3.10),ExceptionGroup/except*andNotRequired/Required(3.11), thedef f[T]()generic syntax (3.12). All of them run on Python 3.14, the version used for every output in this part. Where a detail is newer than 3.10, it is called out.
Topics in this part
Practice
Python workbench โ write and run code here
Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.
Each topic above carries its own exercise and solution โ open a topic and scroll to its exercise. All 6 exercises are also counted on the Python Practice page.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
isinstance(x, SomeProtocol) without @runtime_checkable |
Protocol is static-only by default |
add @runtime_checkable, or just use mypy |
Making a class inherit from a Protocol "to be safe" |
defeats the point; structural typing needs no inheritance | let unrelated classes match by shape |
def first(items: list) -> object: instead of def first[T](items: list[T]) -> T: |
loses the link between input and output type | add the type parameter [T] |
Mixing NotRequired keys with total=False in the same TypedDict |
confusing: now which keys are really required? | pick one style per TypedDict family |
Trusting a TypedDict to check values at run time |
it is a plain dict; Python never checks it |
run mypy, or validate manually for untrusted input (e.g. real webhooks) |
A mapping pattern expecting an exact dict, e.g. case {"status": "ok"}: matching nothing else |
extra keys are allowed; this is normal, not an error | add **rest only if you must capture the extras |
A sequence pattern like case [a, b]: on a dict's .values() when key order was never guaranteed |
works by luck, breaks when the data changes | match the dict itself with a mapping pattern instead |
Plain except Exception: after collecting errors into an ExceptionGroup |
silently loses which original exceptions happened | use except* per exception type |
Mixing except* and plain except in the same try |
not allowed; SyntaxError |
use except* for every clause once you use it once |
Reading str(KeyError("x")) as x |
KeyError's message is repr'd, so you get 'x' with quotes |
compare the underlying .args[0] if you need the raw text |
Quick recap
Protocoldescribes a shape (methods/attributes); classes fit it without inheriting from it.@runtime_checkableletsisinstance()check one.- Modern generics use
def f[T]()andclass Box[T](3.12+);T: (int, float)bounds the type parameter. TypedDictkeys can be individually optional (NotRequired) or individually required (total=False+Required); it is still a plaindictat run time.matchcan test a value's shape: class patterns pull out fields, sequence patterns test length and parts, mapping patterns test some keys; all of them can nest, guard and use OR patterns.ExceptionGroupbundles many failures into oneraise;except*handles one exception type from the group at a time, and the rest keep propagating.- A webhook router is a
matchover a discriminated union ofTypedDicts: one"type"field picks the shape, then the rest of the pattern pulls out the fields you need.
Checklist
- I can write a
Protocoland explain why classes do not need to inherit from it. - I can add
@runtime_checkableand explain whatisinstance()actually checks then. - I can write a generic function and class with
def f[T]()/class Box[T], with a bound where needed. - I can design a
TypedDictfamily usingNotRequiredortotal=False+Required. - I can write a
matchwith a class pattern, a sequence pattern and a mapping pattern, each with a guard. - I can raise an
ExceptionGroupfrom a batch of failures and handle it withexcept*. - I can route a batch of webhook-style events with
matchon a"type"key.