Skip to content

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.

16 min read0/4 questions

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.

Python
def handle(event: dict) -> str: match event: case {"type": "charge.succeeded", "data": {"amount": int(amount), "currency": cur}}: return f"charged {amount / 100:.2f} {cur.upper()}" case {"type": "charge.refunded", "data": {"amount": amount, "reason": reason}}: return f"refunded {amount}, reason: {reason}" case {"type": "charge.refunded", "data": {"amount": amount}}: return f"refunded {amount}, no reason given" case {"type": str(kind)}: return f"ignored event {kind!r}" case _: return "malformed payload" print(handle({"type": "charge.succeeded", "data": {"amount": 1999, "currency": "gbp"}, "id": "evt_1"}))print(handle({"type": "charge.refunded", "data": {"amount": 500}}))print(handle({"type": "dispute.created", "data": {}}))print(handle({"data": {}}))print(handle(["not", "a", "dict"]))
Output
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, True and False compare with is.
  • Capture patterns: a bare name such as case x: always matches and binds the value to x.
  • Wildcard: case _: always matches and binds nothing. _ can appear inside other patterns too.
  • Value patterns: a dotted name such as case Status.PAID: or case http.HTTPStatus.OK: looks up the existing value and compares with ==.
  • Or-patterns: case 200 | 201 | 204:. Every alternative must bind the same names.
  • as bindings: 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.

Predict the outputPython

What does this print?

for v in [True, 1.0, "1"]:
  match v:
      case 1:
          print("one", end=" ")
      case _:
          print("other", end=" ")
Need a nudge? Hints walk you through it.

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.

Python
RED = "red"colour = "blue" match colour: case RED: # captures, does not compare print("matched RED; RED is now", repr(RED)) print("RED after the match:", RED)
Output
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.

Python
from enum import StrEnum class Colour(StrEnum): RED = "red" BLUE = "blue" def describe(c: str) -> str: match c: case Colour.RED: # dotted: compares with == return "warm" case Colour.BLUE: return "cool" case other: # capture on purpose, as the last case return f"unknown colour {other!r}" print(describe("blue"), describe("red"), describe("teal"))
Output
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.

Quick check
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?
Need a nudge? A hint rules out a wrong answer.

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.

Python
def run(line: str) -> str: match line.split(): case []: return "empty line" case ["quit" | "exit"]: return "bye" case ["go", ("north" | "south" | "east" | "west") as direction]: return f"walking {direction}" case ["go", *_]: return "go where? try north, south, east or west" case ["get", item, "from", place]: return f"taking {item} from {place}" case ["say", *words] if words: return "you say: " + " ".join(words) case [cmd, *_]: return f"unknown command {cmd!r}" for line in ["", "exit", "go east", "go up", "get key from desk", "say hello there", "say", "dance"]: print(f"{line!r:22} -> {run(line)}")
Output
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.

Python
def parse(payload: dict) -> str: match payload: case {"version": 2, "user": {"id": int(uid), "email": str(email)}, **rest}: return f"v2 user {uid} <{email}>, other keys: {sorted(rest)}" case {"user_id": int(uid), "email": email}: return f"v1 user {uid} <{email}>" case {"user": {"id": str()}}: return "rejected: id must be an int, not a string" case _: return "unrecognised payload" print(parse({"version": 2, "user": {"id": 7, "email": "ada@example.com", "name": "Ada"}, "trace": "t1"}))print(parse({"user_id": 3, "email": "sam@example.com"}))print(parse({"version": 2, "user": {"id": "7", "email": "x@example.com"}}))print(parse({}))
Output
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.

How case Point(0, y=y) if y > 0 is checked
  1. isinstance(subject, Point)wrong type: this case fails immediately
  2. Point.__match_args__ = ('x', 'y')maps positional subpatterns to attribute names
  3. subject.x == 0first positional subpattern is the literal 0
  4. y = subject.ykeyword subpattern y=y is a capture
  5. guard: y > 0runs last, after names are bound

The type check comes first. A dict or a Line never gets further.

1/5
Python
from dataclasses import dataclass @dataclassclass Point: x: float y: float @dataclassclass Circle: centre: Point radius: float @dataclassclass Rect: corner: Point w: float h: float def describe(shape) -> str: match shape: case Circle(Point(0, 0), r): return f"circle of radius {r} at the origin" case Circle(centre=c, radius=r) if r <= 0: return f"invalid circle at {c}" case Rect(_, w, h) if w == h: return f"square with side {w}" case Rect(w=w, h=h): return f"rectangle {w} by {h}" case _: return "unknown shape" print(describe(Circle(Point(0, 0), 2)))print(describe(Circle(Point(1, 1), -1)))print(describe(Rect(Point(0, 0), 3, 3)))print(describe(Rect(Point(0, 0), 3, 5)))print(describe("triangle")) class Plain: def __init__(self, a): self.a = a try: match Plain(1): case Plain(x): passexcept TypeError as e: print("TypeError:", e)
Output
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.

Python
import ast def simplify(node): match node: case ast.BinOp(left, ast.Add(), ast.Constant(value=0)): return f"{ast.unparse(left)} + 0 -> {ast.unparse(left)}" case ast.BinOp(left, ast.Mult(), ast.Constant(value=1)): return f"{ast.unparse(left)} * 1 -> {ast.unparse(left)}" case ast.BinOp(_, ast.Mult(), ast.Constant(value=0)): return f"{ast.unparse(node)} -> 0" case _: return f"{ast.unparse(node)}: nothing to simplify" for src in ["price + 0", "qty * 1", "(a + b) * 0", "a - b"]: print(simplify(ast.parse(src, mode="eval").body))
Output
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.

Python
from dataclasses import dataclassfrom typing import assert_never @dataclassclass Card: last4: str @dataclassclass BankTransfer: iban: str @dataclassclass Voucher: code: str type Payment = Card | BankTransfer | Voucher def receipt_line(p: Payment) -> str: match p: case Card(last4=digits): return f"card ending {digits}" case BankTransfer(iban=iban): return f"transfer from {iban[:4]}****" case _: assert_never(p) # a checker flags this: Voucher is unhandled print(receipt_line(Card("4242")))try: receipt_line(Voucher("WELCOME10"))except AssertionError as e: print("AssertionError:", e)
Output
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/elif is 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. match is 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 match only 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.

Put it in order5 steps

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.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/6 matched

Match each pattern to what it does.

Choose an item, then its match on the other side.
Key terms
structural pattern matching
The match statement: 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 if condition 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.