Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

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 with TypedDict, match deeply nested data with match, and report many failures at once with ExceptionGroup / except*. Time: ~1 hour

What you will learn

  • Protocol: a type that describes a shape (methods/attributes), not a base class
  • @runtime_checkable: letting isinstance() check a Protocol
  • Generics you write yourself, with the modern syntax: def f[T](), class Box[T]
  • TypedDict in depth: NotRequired, Required, and one TypedDict inheriting another
  • match going deeper: class patterns, sequence patterns, mapping patterns, nested patterns
  • ExceptionGroup and except*: 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), structural match (3.10), ExceptionGroup/except* and NotRequired/Required (3.11), the def 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

  • Protocol describes a shape (methods/attributes); classes fit it without inheriting from it. @runtime_checkable lets isinstance() check one.
  • Modern generics use def f[T]() and class Box[T] (3.12+); T: (int, float) bounds the type parameter.
  • TypedDict keys can be individually optional (NotRequired) or individually required (total=False + Required); it is still a plain dict at run time.
  • match can 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.
  • ExceptionGroup bundles many failures into one raise; except* handles one exception type from the group at a time, and the rest keep propagating.
  • A webhook router is a match over a discriminated union of TypedDicts: one "type" field picks the shape, then the rest of the pattern pulls out the fields you need.

Checklist

  • I can write a Protocol and explain why classes do not need to inherit from it.
  • I can add @runtime_checkable and explain what isinstance() 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 TypedDict family using NotRequired or total=False + Required.
  • I can write a match with a class pattern, a sequence pattern and a mapping pattern, each with a guard.
  • I can raise an ExceptionGroup from a batch of failures and handle it with except*.
  • I can route a batch of webhook-style events with match on a "type" key.

Search the guide