Skip to content
devtoolbox.cc

Python · Chapter 13 of 21

Python match and case: structural pattern matching by example

15 min study · Examples checked with Python 3.14 and 3.15 ·

The match statement checks a value against a list of patterns and runs the first one that fits. A pattern can test a value’s shape (a list of three items, a dictionary with a type key, an object of a certain class) and pull pieces out of it in the same step. That makes match a good fit for commands, parsed messages and API events that come in several forms. This chapter builds a small command interpreter and an event handler, and points out the two traps that catch most newcomers.

Literal patterns and alternatives

def reply(command: str) -> str:
    match command.strip().casefold():
        case "help" | "?":
            return "commands: add, list, quit"
        case "quit" | "exit":
            return "bye"
        case other:
            return f"unknown command: {other}"

for text in ["?", "  QUIT ", "dance"]:
    print(reply(text))
# commands: add, list, quit / bye / unknown command: dance

Python evaluates the subject once, then tries each case from top to bottom. Only the first match runs; there is no fall-through to the next case, and no break is needed. | lists alternatives. The last case, a bare name, matches anything and binds the value to that name; case _: does the same without binding. If no case matches and there is no catch-all, nothing happens.

Trap one: a bare name captures, it doesn’t compare

QUIT = "quit"
command = "add"

match command:
    case QUIT:              # captures! QUIT is now "add"
        print("matched", QUIT)

from enum import Enum

class Cmd(Enum):
    QUIT = "quit"
    ADD = "add"

match Cmd(command):
    case Cmd.QUIT:          # dotted name: compared by value
        print("quit")
    case Cmd.ADD:
        print("add")
# matched add / add

In a pattern, a plain name is always a capture target, even if a variable of that name already exists. The first match therefore matches every value and silently rebinds QUIT. Python refuses to compile a bare capture that is followed by more cases, but as the last case it slips through. To compare against a constant, use a dotted name, such as an Enum member or module.CONSTANT, or a guard (case x if x == QUIT).

Sequence patterns

def parse(tokens: list[str]) -> dict:
    match tokens:
        case ["list"]:
            return {"action": "list"}
        case ["add", title, minutes] if minutes.isdigit():
            return {"action": "add", "title": title, "minutes": int(minutes)}
        case ["tag", title, *tags] if tags:
            return {"action": "tag", "title": title, "tags": tags}
        case _:
            raise ValueError(f"cannot parse {tokens!r}")

print(parse("add Loops 15".split()))   # {'action': 'add', 'title': 'Loops', 'minutes': 15}
print(parse(["tag", "Loops", "basics", "core"]))
# {'action': 'tag', 'title': 'Loops', 'tags': ['basics', 'core']}

A sequence pattern matches lists, tuples and other sequences with the right number of items, binding each position to a name. *tags collects the rest into a list (possibly empty, which is why the guard checks it). Strings are deliberately not treated as sequences here, so "add" never matches [a, b, c]. Patterns check shape, not meaning: ["add", "Loops", "fifteen"] has the right shape, and only the guard stops it.

Dictionary patterns for JSON-like data

Data from APIs and JSON files arrives as nested dictionaries and lists. Mapping patterns match on the keys you name and ignore any others:

def handle(event: dict) -> str:
    match event:
        case {"type": "completed", "lesson": {"id": int(lesson_id), "title": str(title)}}:
            return f"lesson {lesson_id} done: {title}"
        case {"type": "enrolled", "course": str(course), **rest}:
            return f"joined {course}; extra keys: {sorted(rest)}"
        case {"type": str(kind)}:
            return f"ignored event type {kind!r}"
        case _:
            return "not an event"

print(handle({"type": "completed", "lesson": {"id": 7, "title": "Loops"}, "at": "09:00"}))
print(handle({"type": "enrolled", "course": "Django", "source": "web"}))
print(handle({"type": "paused"}), "|", handle(["type"]))
# lesson 7 done: Loops
# joined Django; extra keys: ['source']
# ignored event type 'paused' | not an event

Patterns nest, so one case can reach into the lesson dictionary. int(lesson_id) and str(title) are class patterns: they check the type and bind the value, but do not convert, so {"id": "7"} would not match. One subtlety: bool is a subclass of int, so True matches int(...); add a guard if that matters. Extra keys never prevent a match, and **rest collects them when you need them. To reject unknown keys, check explicitly, or validate with a schema (for JSON, see the JSON Schema validator).

Class patterns and guards

from dataclasses import dataclass

@dataclass
class Lesson:
    title: str
    minutes: int

@dataclass
class Quiz:
    title: str
    questions: int

def label(item) -> str:
    match item:
        case Lesson(title, minutes) if minutes <= 15:
            return f"short lesson: {title}"
        case Lesson(title=title):
            return f"lesson: {title}"
        case Quiz() as quiz:
            return f"quiz with {quiz.questions} questions"
        case _:
            return "unknown item"

print([label(x) for x in [Lesson("Loops", 10), Lesson("OOP", 40), Quiz("Q2", 5), 42]])
# ['short lesson: Loops', 'lesson: OOP', 'quiz with 5 questions', 'unknown item']

Lesson(title=title) matches any Lesson instance and binds its title attribute; Quiz(questions=0) would match only quizzes with no questions. Positional sub-patterns like Lesson(title, minutes) rely on the class’s __match_args__, which dataclasses generate in field order; keyword patterns are clearer and survive reordering. A guard (if ...) is checked after the pattern matches; if it is false, matching continues with the next case. as binds the whole matched object, here so the case can read quiz.questions.

Trap two, and when to use if instead

Names bound by a pattern stay bound after the match statement, like any assignment. If a pattern fails partway, some names may already be bound, so only use names from the case that actually ran.

match is not a faster if. For a single condition, or a chain of comparisons on one value, if/elif is shorter and clearer. For dispatching on a fixed string to one function each, a dictionary of functions works well. Reach for match when the shape of the data is what decides: a list with a variable tail, nested dictionaries, or one of several classes.

Practice

Extend parse with ["open", lesson_id], accepted only when lesson_id is a positive whole number, returning {"action": "open", "id": <int>}. Then add an event case for {"type": "rated", "lesson": int(id), "stars": int(stars)} that only matches when stars is between 1 and 5.

Answer check: parse(["open", "3"]) gives {'action': 'open', 'id': 3}, while ["open", "0"], ["open", "x"] and ["open"] fall through to the ValueError. Use a guard such as if lesson_id.isdigit() and int(lesson_id) > 0. For the rating, if 1 <= stars <= 5 in the guard, and remember that the case must come before the generic {"type": str(kind)} case.

Summary

match tries cases in order and runs the first that fits. Patterns match literals, sequences (with *rest), dictionaries (extra keys allowed), and classes (by type and attributes), and bind parts of the value as they go. Bare names capture, so use dotted names for constants. Guards add conditions, patterns don’t convert types, and plain if remains the better choice for simple tests.

All Python chapters