match Statements Destructure Data Shapes

Structural pattern matching unwraps dicts and sequences in one case ladder: literal keys bind capture variables and guards reject values the shape alone cannot.

PythonData Integrity

Code

pythonsnippet
34 lines
def handle_event(event):
    match event:
        case {"type": "deploy", "service": service, "env": "prod"}:
            return f"deploying {service} to prod"
        case {"type": "scale", "service": service, "replicas": n} if n > 0:
            return f"scaling {service} to {n} replicas"
        case {"type": kind, **rest}:
            return f"unhandled type {kind}: {sorted(rest)}"
        case _:
            return "malformed event, missing type"


def bounds(reading):
    match reading:
        case [low, high] if low <= high:
            return f"range {low}..{high}"
        case [single]:
            return f"single point {single}"
        case []:
            return "no readings"
        case _:
            return f"unexpected shape of {len(reading)} values"


for event in [
    {"type": "deploy", "service": "billing", "env": "prod"},
    {"type": "scale", "service": "auth", "replicas": 5},
    {"type": "scale", "service": "auth", "replicas": 0},  # the guard rejects it
    {"type": "ping"},
]:
    print(handle_event(event))

for reading in [[18, 24], [7], [], [1, 2, 3]]:
    print(bounds(reading))

How it works

match Statements Destructure Data Shapes comes down to the functions handle_event and bounds.

Repetition is confined to for event in [ — the rest of the file is straight-line.

Using it

Signature: def handle_event(event)

Import handle_event from the file and call it — the rest of the code is implementation detail.

Key statements

def bounds(reading):
    match reading:
        case [low, high] if low <= high:
            return f"range {low}..{high}"
        case [single]:
            return f"single point {single}"
        case []:
            return "no readings"
        case _:
            return f"unexpected shape of {len(reading)} values"

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `handle_event`, `bounds` at load time.