Structural pattern matching — pattern-based control flow (similar to switch).
1# Basic matching2def handle_command(command):3 match command.split():4 case ["quit"]:5 return "Goodbye"6 case ["hello", name]:7 return f"Hello, {name}!"8 case ["add", *numbers]:9 return sum(int(n) for n in numbers)10 case _:11 return "Unknown command"1213# Class pattern matching14class Point:15 def __init__(self, x, y):16 self.x = x17 self.y = y1819def classify(point):20 match point:21 case Point(x=0, y=0):22 return "origin"23 case Point(x=x, y=0):24 return f"x-axis at {x}"25 case Point(x=0, y=y):26 return f"y-axis at {y}"27 case Point():28 return "general point"
Features:
if.|.