caseExpert Examples

Defines a pattern branch inside a match statement (3.10+)

Case pattern compilation

How different case patterns compile to bytecode.

python
import dis

def match_types(x):
    match x:
        case int():
            return "int"
        case str():
            return "str"
        case _:
            return "other"

def match_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

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.

Want to try these examples interactively?

Open Expert Playground