case — Intermediate Examples
Defines a pattern branch inside a match statement (3.10+)
Case with capture and type patterns
Extracting values and checking types in case clauses.
python
# Type patterns with capture def process(value): match value: case int(n): print(f"Integer: {n}") case str(s): print(f"String: {s!r}") case list() as items: print(f"List with {len(items)} items") case dict() as d: print(f"Dict with keys: {list(d.keys())}") case None: print("None value") case _: print(f"Other: {type(value).__name__}") for v in [42, "hello", [1, 2], {"a": 1}, None, 3.14]: process(v) # Starred patterns match [1, 2, 3, 4, 5]: case [first, *rest]: print(f"First: {first}, rest: {rest}") match [1]: case [x, *rest] if not rest: print(f"Single element: {x}")
case patterns can check types and capture values simultaneously. Use * patterns for variable-length sequences.
Nested case patterns
Pattern matching on complex nested data.
python
# Command parser commands = [ {"cmd": "move", "args": {"direction": "north", "speed": 5}}, {"cmd": "attack", "args": {"target": "dragon"}}, {"cmd": "heal", "args": {}}, {"cmd": "unknown"}, ] for command in commands: match command: case {"cmd": "move", "args": {"direction": d, "speed": int(s)}}: print(f"Move {d} at speed {s}") case {"cmd": "attack", "args": {"target": str(t)}}: print(f"Attack {t}") case {"cmd": str(c), "args": dict() as args} if not args: print(f"Command {c} with no args") case {"cmd": str(c)}: print(f"Command {c} (no args key)")
Expected Output
Move north at speed 5 Attack dragon Command heal with no args Command unknown (no args key)
case patterns can destructure deeply nested dicts and lists. Guards add extra conditions beyond structural matching.
Want to try these examples interactively?
Open Intermediate Playground