Structural matching

2 snippets in Python

PYPython

match / case (Structural Pattern Matching)

PY · Control Flow
Syntax
match subject:
    case pattern:
        ...
Example
command = {"action": "move", "x": 10, "y": 20}

match command:
    case {"action": "move", "x": x, "y": y}:
        print(f"Moving to ({x}, {y})")
    case {"action": "stop"}:
        print("Stopping")
    case _:
        print("Unknown command")
Output
Moving to (10, 20)

Note match/case (Python 3.10+) is structural pattern matching, not just a switch. It can destructure dicts, sequences, and objects in the pattern.

Match/Case Pattern Types

PY · Modern Features
Syntax
match value:
    case pattern:
        ...
Example
def describe(value):
    match value:
        case int(n) if n > 0:
            return f"positive int: {n}"
        case str(s) if len(s) > 5:
            return f"long string: {s!r}"
        case [first, *rest]:
            return f"list starting with {first}, {len(rest)} more"
        case {"type": "error", "code": code}:
            return f"error code {code}"
        case _:
            return "something else"

print(describe(42))
print(describe([1, 2, 3]))
print(describe({"type": "error", "code": 500}))
Output
positive int: 42
list starting with 1, 2 more
error code 500

Note Match/case supports literal, capture, sequence, mapping, class, guard (if), and OR (|) patterns. The _ wildcard matches anything.

Frequently asked questions

How does Python handle structural matching?
Python covers this with 2 copy-ready snippets on this page. The "match / case (Structural Pattern Matching)" snippet in Python uses `match subject:`.
Which code does the Python example use?
The "match / case (Structural Pattern Matching)" snippet uses `match subject:`, from the Control Flow section of the Python cheat sheet.
What other Python snippets are shown for "structural matching"?
Besides "match / case (Structural Pattern Matching)", this page also shows "Match/Case Pattern Types".
Is there anything to watch out for?
Yes. For "match / case (Structural Pattern Matching)": match/case (Python 3.10+) is structural pattern matching, not just a switch. It can destructure dicts, sequences, and objects in the pattern.