Match alternatives and their contents

Lesson 20 of 20 · Functional Python: values, behavior, and choices

Python 3.10 introduced structural pattern matching. match evaluates a subject, then tests case patterns in order. The first match runs. _ is a wildcard; without a matching case execution continues after the match.

from dataclasses import dataclass

@dataclass(frozen=True)
class Ready:
    location: str

@dataclass(frozen=True)
class Delayed:
    days: int

def message(outcome: Ready | Delayed) -> str:
    match outcome:
        case Ready(location=place):
            return f"Collect from {place}"
        case Delayed(days=n) if n > 1:
            return f"Wait {n} days"
        case Delayed(days=n):
            return f"Wait {n} day"
        case _:
            raise TypeError("unexpected outcome")

print(message(Ready("desk")))
print(message(Delayed(3)))
print(message(Delayed(1)))
Collect from desk
Wait 3 days
Wait 1 day

A class pattern checks the class and extracts the named attribute into place or n. The if n > 1 guard runs after that pattern matches; if false, the next case is tried. This illustration assumes positive delay values; the annotation does not enforce them. _ handles other runtime types rather than proving all intended cases are covered.

Patterns can also inspect combinations, for example match (source, destination) followed by case ("audio", "preview"). For enum choices use a qualified member such as Signal.GO: a bare name in a pattern generally captures the subject rather than comparing with an existing variable. Pattern matching does not enforce exhaustiveness at runtime; a simple if chain may be clearer for a small decision.

Chapter index