import dis
defmatch_example(x):
match x:
case1:
return"one"case [a, b]:
returnf"pair: {a}, {b}"case {"key": v}:
returnf"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 caseprint(f"\nTest: {match_example(1)}")
print(f"Test: {match_example([3, 4])}")
print(f"Test: {match_example({'key': 'val'})}")
Output
Click "Run" to execute your code
match compiles to a decision tree of type checks, comparisons, and conditional jumps. Each pattern type uses different bytecode sequences to test and destructure.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?