match — Expert Examples
Begins a structural pattern matching block (3.10+)
Match internals
How match/case compiles.
python
import dis def match_example(x): match x: case 1: return "one" case [a, b]: return f"pair: {a}, {b}" case {"key": v}: return f"dict with key={v}" case _: return "other" dis.dis(match_example) # match compiles to a series of type checks and comparisons: # - Literal patterns use COMPARE_OP # - Sequence patterns check type + length # - Mapping patterns check keys # - Class patterns use isinstance + attribute access # Each failed pattern jumps to the next case print(f"\nTest: {match_example(1)}") print(f"Test: {match_example([3, 4])}") print(f"Test: {match_example({'key': 'val'})}")
Expected Output
one Test: pair: 3, 4 Test: dict with key=val
match compiles to a decision tree of type checks, comparisons, and conditional jumps. Each pattern type uses different bytecode sequences to test and destructure.
Want to try these examples interactively?
Open Expert Playground