Lesson 27 of 52Pythonic Python
Structural Pattern Matching
Use match to destructure sequences, dicts and objects, avoid the capture-name trap, and know when a plain if or a dispatch dict is clearer.
A payments provider sends your service webhooks: a dict that might be a charge, a refund or a dispute, each with different nested fields, some optional, some added last month. The old handler is eighty lines of if event.get("type") == ... followed by if "amount" in event["data"], and every new event type makes it worse. Structural pattern matching lets you write the shape you expect and pull out the parts you need in one step. You saw the simple form in Conditions, where match looked like a cleaner elif chain. This lesson covers what it really does: destructuring data, and the traps that make it bite.
match is not a switch
In C, Java or JavaScript, switch compares one value against constants. Python's match does more. Each case is a pattern that can check a value's type and structure and, at the same time, bind parts of it to names. The cases are tried top to bottom, and the first one that matches runs. There is no fall-through and no break.
Press Run (⌘ Enter) to see what happens.Read the first case aloud: "a mapping whose type is charge.succeeded and whose data is a mapping with an integer amount and a currency; call those amount and cur." One line does the type check, the nested key checks and the variable extraction that would otherwise take six. The extra id key did not stop the match; more on that below.
The building blocks
Every pattern is built from a handful of pieces. Learn them as a small grammar.
- Literal patterns:
case 404:,case "quit":,case None:. Numbers and strings compare with==.None,TrueandFalsecompare withis. - Capture patterns: a bare name such as
case x:always matches and binds the value tox. - Wildcard:
case _:always matches and binds nothing._can appear inside other patterns too. - Value patterns: a dotted name such as
case Status.PAID:orcase http.HTTPStatus.OK:looks up the existing value and compares with==. - Or-patterns:
case 200 | 201 | 204:. Every alternative must bind the same names. asbindings:case [1, 2] as pair:matches the subpattern and also binds the whole value.- Guards:
case n if n > 100:. The pattern matches first, binds names, and then the guard decides.
Literals compare with ==, which has a consequence that surprises people. True == 1 and 1.0 == 1, so case 1: matches both.
What does this print?
for v in [True, 1.0, "1"]:
match v:
case 1:
print("one", end=" ")
case _:
print("other", end=" ")The capture-name trap
This is the most famous bug in pattern matching and a favourite interview question. A bare name in a pattern is never a comparison. It is always a capture, even when a variable with that name already exists.
Press Run (⌘ Enter) to see what happens.case RED: matched "blue", and it overwrote the module-level RED. If you put a capture like this before other cases, Python refuses to compile it, with SyntaxError: name capture 'RED' makes remaining patterns unreachable. That error is a gift: it catches the bug at import time. But when the bare name is the last case, you get no warning at all, just wrong behaviour.
The fix is to make the name dotted, so Python treats it as a value lookup. Put constants in an enum or a class, or import the module and refer to module.NAME.
Press Run (⌘ Enter) to see what happens.This is one more reason to keep fixed sets of values in an enum, as you saw in the Enums lesson: dotted names make match both safe and readable.
LIMIT = 10 is defined at module level. A function contains match n: case LIMIT: return 'at limit' as its only case. What happens when you call it with n = 3?Sequence patterns
Square brackets or parentheses match sequences: lists, tuples, range objects, anything registered as collections.abc.Sequence. The length must fit, and one starred name can absorb the rest.
This is the classic command interpreter: split a line into words and match on the list.
Press Run (⌘ Enter) to see what happens.Notice that "say" on its own failed the guard (words was empty) and fell through to the last case. A guard failing simply moves on to the next case.
One deliberate exception: strings are not matched as sequences, and neither are bytes or bytearray. Without that rule, case [a, b]: would match the two-character string "hi", which would be a bug factory. Tuples and lists are interchangeable: case [x, y]: matches (1, 2) too. If the type matters, add a class pattern such as case list([x, y]): or case tuple((x, y)):.
Mapping patterns
Curly braces match mappings: dict and anything registered as collections.abc.Mapping. Keys must be literals or dotted value patterns, and each value is itself a pattern.
The key rule: extra keys are allowed. A mapping pattern checks that the listed keys exist and match. It ignores everything else. That is exactly right for JSON from other services, where new fields appear without warning. If you want the leftovers, use **rest.
Press Run (⌘ Enter) to see what happens.This is a tidy way to support two API versions side by side during a migration. It is not a replacement for real validation at the edge of your system. For request bodies, Pydantic gives you error messages per field, coercion and an OpenAPI schema. Pattern matching shines one step later, when you already have trusted data in a few known shapes and need to branch on which one it is.
Class patterns
ClassName(...) patterns match objects. Python first checks isinstance(subject, ClassName), then reads the named attributes and matches each against its subpattern.
The type check comes first. A dict or a Line never gets further.
Press Run (⌘ Enter) to see what happens.A few rules worth knowing. Keyword subpatterns (radius=r) always work, positional ones need __match_args__. Dataclasses generate it from the fields, leaving out kw_only ones. For the built-in types int, str, float, bool, bytes, list, tuple, dict, set and a few others, a single positional subpattern matches the whole subject, so case int(n): means "if it is an int, call it n", and case str() as s: does the same with an as binding.
Walking trees
Class patterns nest, which makes them excellent for tree-shaped data. The ast module's node classes all define __match_args__, so a linter or code-mod rule can read like the code it looks for.
Press Run (⌘ Enter) to see what happens.Exhaustiveness with assert_never
When the subject is a union of types or an enum, a type checker can prove that your cases cover every possibility. End with case _: assert_never(x). If a later change adds a new type to the union, mypy or pyright reports an error on that line, and at runtime assert_never raises AssertionError instead of silently returning None.
Press Run (⌘ Enter) to see what happens.This pattern, a closed union of small dataclasses plus a match with assert_never, is how Python expresses what other languages call sum types or tagged unions. It is a strong design for state machines and message handling: each state carries exactly its own data, and the checker tells you every place that must change when a state is added.
When not to use match
match is a tool for shapes. For plain values it is often more ceremony than help.
- Simple equality on one value, two or three branches:
if/elifis shorter and every Python developer reads it instantly. - Choosing a function by key: a dict dispatch table,
HANDLERS[event_type](payload), is shorter, extensible at runtime and testable per handler.matchis static: you cannot add a case from another module. - Type-based behaviour that other modules extend:
functools.singledispatch, from the functools and itertools lesson, keeps the registry open. - Validating untrusted input: use Pydantic or a schema library, which produce useful error messages. A failed
matchonly tells you "no case matched".
Also remember that cases are tried in order, one by one. There is no jump table, so a match with fifty cases costs about the same as fifty if checks. Put specific cases before general ones, or the general case will swallow them, and put the most common shapes first if the code is hot.
Two subtle rules the docs warn about
Names can leak from failed cases. A pattern binds names as it goes, so a case that fails partway, or whose guard is false, can still have assigned some names. CPython does this today, but the language reference does not promise which names are bound after a failed match. Never read a capture variable outside the case that matched it.
Mapping and class patterns read attributes and keys. A class pattern calls getattr on the subject, which can run a property or __getattr__. A mapping pattern uses the mapping's get method. If those have side effects or are slow (an ORM lazy-loading a relation, for example), a match can trigger database queries you did not expect. Match on plain data where you can.
These cases match the same event dict. Order them from the one that must come first to the one that must come last, so none is unreachable.
- Tap the steps below in the right order.
Match each pattern to what it does.
- structural pattern matching
- The
matchstatement: checking a value's type and shape and binding its parts to names in one step. - capture pattern
- A bare name in a case. It always matches and binds the value to that name.
- value pattern
- A dotted name like
Colour.RED. It looks up an existing value and compares with==. - guard
- An
ifcondition after a pattern, checked only after the pattern has matched and bound its names. - mapping pattern
{'key': pattern}: requires the listed keys and ignores extra keys unless you collect them with**rest.- __match_args__
- A class attribute naming which attributes positional subpatterns map to. Dataclasses generate it.
- sum type
- A value that is exactly one of a closed set of variants, written in Python as a union of dataclasses.