Structural Pattern Matching
Introduced in Python 3.10, the match statement is a revolutionary addition to the language. While it looks like a “switch” statement from other languages, it is fundamentally different. It doesn’t just check values; it checks the structure and content of your data simultaneously.
1. Basic Value Matching
Section titled “1. Basic Value Matching”At its simplest, match replaces a long chain of if-elif-else.
status = 404
match status: case 200: print("OK") case 404: print("Not Found") case 500 | 501 | 502: # Pipe '|' acts as 'OR' print("Server Error") case _: print("Unknown Status")The Wildcard (_)
Section titled “The Wildcard (_)”The underscore is the “catch-all” pattern. If no other case matches, this one will. It is the equivalent of the else block.
2. Structural Matching & Variable Capture
Section titled “2. Structural Matching & Variable Capture”The true power of match is the ability to deconstruct data.
def process_command(cmd): match cmd.split(): case ["quit"]: print("Shutting down...") case ["load", filename]: print(f"Loading data from {filename}") case ["move", ("up" | "down" | "left" | "right") as direction, distance]: print(f"Moving {distance} units {direction}") case _: print("Invalid command structure.")
process_command("move left 10") # Variable 'direction' and 'distance' are automatically assigned!Context: In the example above, Python checks if the list has three items, if the first is “move”, if the second is a valid direction, and then extracts the values into local variables.
3. Matching Dictionaries and Objects
Section titled “3. Matching Dictionaries and Objects”You can match against keys and values in a dictionary.
response = {"status": "error", "code": 401, "message": "Unauthorized"}
match response: case {"status": "success", "data": content}: print(f"Success! Received: {content}") case {"status": "error", "code": 401}: print("Login required.") case {"status": "error", "message": msg}: print(f"General Error: {msg}")4. Guard Clauses
Section titled “4. Guard Clauses”You can add an if statement (a Guard) to a case to perform additional logic that pattern matching alone can’t handle.
match point: case (x, y) if x == y: print("Point is on the diagonal line.") case (x, y) if x > 0 and y > 0: print("Point is in the first quadrant.")5. Under the Hood: No Fall-Through
Section titled “5. Under the Hood: No Fall-Through”In languages like C or Java, if you forget a break statement at the end of a case, the execution “falls through” into the next case.
Python does not have fall-through. Once a match is found, its block is executed, and the program immediately exits the match statement. This makes code safer and more predictable.
6. Comparison Table
Section titled “6. Comparison Table”| Feature | if-elif-else | match-case |
|---|---|---|
| Primary Focus | Boolean conditions. | Data structure and values. |
| Complexity | Becomes hard to read with deep nesting. | Stays flat and readable. |
| Data Extraction | Requires manual indexing/slicing. | Automatic via Variable Capture. |
| Performance | O(n) (checks every line). | Optimized by the interpreter. |