Skip to content

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.


At its simplest, match replaces a long chain of if-elif-else.

http_status.py
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 underscore is the “catch-all” pattern. If no other case matches, this one will. It is the equivalent of the else block.


The true power of match is the ability to deconstruct data.

command_parser.py
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.


You can match against keys and values in a dictionary.

api_response.py
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}")

You can add an if statement (a Guard) to a case to perform additional logic that pattern matching alone can’t handle.

guard_example.py
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.")

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.


Featureif-elif-elsematch-case
Primary FocusBoolean conditions.Data structure and values.
ComplexityBecomes hard to read with deep nesting.Stays flat and readable.
Data ExtractionRequires manual indexing/slicing.Automatic via Variable Capture.
PerformanceO(n) (checks every line).Optimized by the interpreter.