← Back to Python, page 3

python-0052 · Medium mid

How does structural pattern matching (match/case) work beyond simple value checks?

match compares a subject against case patterns that can test literals, sequences, mappings, class shapes and types, binding variables from the matched parts. Guards with if add conditions, | combines alternatives, and _ is the wildcard. It shines when handling structured data such as parsed commands or JSON events.

Full answer
python
from dataclasses import dataclass
@dataclass
class Point:
    x: int
    y: int

def describe(event):
    match event:
        case {"type": "click", "pos": [x, y]} if x < 0 or y < 0:
            return "click off-screen"
        case {"type": "click", "pos": [x, y]}:
            return f"click at {x},{y}"
        case {"type": "key", "key": "q" | "Q"}:
            return "quit"
        case Point(x=0, y=0):
            return "origin"
        case Point(x=x, y=y):
            return f"point {x},{y}"
        case [first, *rest]:
            return f"list starting {first}, {len(rest)} more"
        case _:
            return "unknown"

for e in [{"type": "click", "pos": [3, 4]}, {"type": "click", "pos": [-1, 2]}, {"type": "key", "key": "Q", "extra": 1},
          Point(0, 0), Point(2, 5), [1, 2, 3], "hello"]:
    print(describe(e))

Output:

text
click at 3,4
click off-screen
quit
origin
point 2,5
list starting 1, 2 more
unknown

Cases are tried in order, so the guarded off-screen case comes before the general click case. Mapping patterns match if the listed keys exist, ignoring extra keys such as 'extra'. Class patterns check the type and attributes, and sequence patterns destructure lists with *rest. A plain string does not match the sequence pattern, because strings are deliberately excluded from sequence patterns, so it falls through to _. Remember that a bare name in a case captures rather than compares; use dotted names or literals for constants.

python
from dataclasses import dataclass
@dataclass
class Point:
    x: int
    y: int

def describe(event):
    match event:
        case {"type": "click", "pos": [x, y]} if x < 0 or y < 0:
            return "click off-screen"
        case {"type": "click", "pos": [x, y]}:
            return f"click at {x},{y}"
        case {"type": "key", "key": "q" | "Q"}:
            return "quit"
        case Point(x=0, y=0):
            return "origin"
        case Point(x=x, y=y):
            return f"point {x},{y}"
        case [first, *rest]:
            return f"list starting {first}, {len(rest)} more"
        case _:
            return "unknown"

for e in [{"type": "click", "pos": [3, 4]}, {"type": "click", "pos": [-1, 2]}, {"type": "key", "key": "Q", "extra": 1},
          Point(0, 0), Point(2, 5), [1, 2, 3], "hello"]:
    print(describe(e))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Patterns match shapes and bind names
  • Cases run in order
  • Guards add conditions
  • Mapping patterns ignore extra keys
  • Bare names capture, dotted names compare

Common mistakes

  • Writing case STATUS: expecting a comparison
  • Putting general cases before specific ones

Follow-ups

  • How does __match_args__ work?
  • When is a dict of handlers simpler than match?

Tips

  • Order cases from specific to general