Mastery
Mastery/Python/E. Typing & modern syntax
T1 · high-leverage

match/case structural pattern matching (PEP 634)

Beyond simple value matching, case patterns can destructure sequences, mappings, and objects (via __match_args__), combine alternatives with |, and attach a case ... if <guard>: condition. It's closer to real pattern matching (Rust/Haskell-style) than a fancy switch -- it binds names as it matches.

python
def describe(x):
    match x:
        case 0:
            return "zero"
        case int() | float() if x < 0:
            return "negative number"
        case [a, b]:
            return f"pair: {a}, {b}"
        case [a, *rest]:
            return f"list starting with {a}, {len(rest)} more"
        case {"type": "point", "x": px, "y": py}:
            return f"point dict at {px},{py}"
        case str():
            return "a string"
        case _:
            return "something else"

for val in [0, -5, [1, 2], [1, 2, 3, 4], {"type": "point", "x": 1, "y": 2}, "hi", 3.5]:
    print(f"{val!r:34} -> {describe(val)}")

A class with __match_args__ can be destructured positionally, and guards can compare the bound fields to each other:

python
class Point:
    __match_args__ = ("x", "y")
    def __init__(self, x, y):
        self.x, self.y = x, y

def classify(p):
    match p:
        case Point(0, 0):
            return "origin"
        case Point(x, 0):
            return f"on x-axis at {x}"
        case Point(x, y) if x == y:
            return "on the diagonal"
        case Point():
            return "somewhere else"

for p in [Point(0, 0), Point(5, 0), Point(3, 3), Point(1, 2)]:
    print(f"({p.x},{p.y}) -> {classify(p)}")

Interview angle

A "do you know Python 3.10+" signal question, and a good practical exercise is asking a candidate to destructure a nested structure (a dict inside a list, or a custom class via __match_args__) rather than just matching literal values — that's what separates match from a dressed-up if/elif chain, and testing it directly shows whether someone understands it's real structural pattern matching.

In the industry

Adoption is still gradual — codebases with a minimum Python version below 3.10 can't use it at all, and many teams are conservative about adopting it broadly since if/elif remains perfectly idiomatic for simple cases. Where it earns its place is exactly the scenario shown here: dispatching on the shape of data (a parsed JSON payload, an AST-like structure, a small sealed set of message types) where the destructuring is doing real work, not just replacing a value comparison.