import dis
defmatch_types(x):
match x:
caseint():
return"int"casestr():
return"str"case _:
return"other"defmatch_sequence(x):
match x:
case [a, b]:
return a + b
case [a, b, c]:
return a + b + c
print("Type matching:")
dis.dis(match_types)
print("\nSequence matching:")
dis.dis(match_sequence)
# Type patterns compile to isinstance() checks# Sequence patterns check: is sequence? len matches? extract items# The compiler generates optimized decision trees
Output
Click "Run" to execute your code
case patterns compile to isinstance checks (for type patterns), length checks + indexing (for sequences), and key lookups (for mappings). The compiler orders checks to fail fast.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?