Python Match...Case
Python's match...case statement, introduced in Python 3.10, brings Structural Pattern Matching to the language. While it looks similar to a switch statement found in other languages (like JavaScript or C++), it is significantly more powerful because it allows you to match data structures, unpack objects, extract values, and apply conditional guards.
1. Basic Literal Matching
At its simplest, match...case acts as a cleaner, more readable alternative to a long chain of if...elif...else statements when checking a variable against specific literal values.
def http_status(status_code):
match status_code:
case 200:
return "OK"
case 400:
return "Bad Request"
case 401 | 403: # Using the OR operator '|'
return "Not Authorized"
case 404:
return "Not Found"
case _: # Wildcard / Default case (like 'else')
return "Unknown Status"
print(http_status(200)) # Output: OK
print(http_status(403)) # Output: Not Authorized
print(http_status(500)) # Output: Unknown Status
2. Matching Data Structures (Destructuring)
Structural pattern matching shines when dealing with collections like lists or tuples. You can match the shape and structure of data and bind parts of it to variables simultaneously.
def process_command(command):
match command.split():
case ["quit"]:
print("Exiting application...")
case ["load", filename]:
print(f"Loading file: {filename}")
case ["move", direction, distance]:
print(f"Moving {direction} by {distance} units")
case _:
print("Invalid command syntax.")
process_command("load data.csv") # Output: Loading file: data.csv
process_command("move north 50") # Output: Moving north by 50 units
3. Adding Guards (if clauses)
You can refine your case patterns by adding an extra if condition called a guard. The pattern only matches if both the structural match succeeds and the guard evaluates to True.
def analyze_point(point):
match point:
case (0, 0):
print("Origin")
case (x, 0):
print(f"On the X-axis at x={x}")
case (0, y):
print(f"On the Y-axis at y={y}")
case (x, y) if x == y:
print(f"On the diagonal line where x=y={x}")
case (x, y):
print(f"Point located at x={x}, y={y}")
analyze_point((0, 5)) # Output: On the Y-axis at y=5
analyze_point((3, 3)) # Output: On the diagonal line where x=y=3
4. Matching Objects (Class Patterns)
You can match instances of user-defined classes against patterns, checking their attributes directly without needing manual dot-notation lookups inside the handler.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def locate(p):
match p:
case Point(x=0, y=0):
print("At the origin")
case Point(x=0, y=y):
print(f"On Y-axis at {y}")
case Point(x=x, y=0):
print(f"On X-axis at {x}")
case Point(x=x, y=y):
print(f"Custom coordinates: ({x}, {y})")
locate(Point(0, 10)) # Output: On Y-axis at 10