Python Match (Structural Pattern Matching)
Match Statement (Python 3.10+)
The `match` statement introduces structural pattern matching, similar to `switch` in other languages but with more flexibility. It allows checking a value against multiple patterns and executing code for the first match.
Example
# Basic match statement
def http_status(code):
match code:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown status code"
print(http_status(200))
print(http_status(404))
print(http_status(999))
Output
OK Not Found Unknown status code
Pattern Matching with Data Structures
Match statements can destructure and match complex data structures like lists, tuples, and dictionaries.
Example
# Pattern matching with lists
def process_command(command):
match command:
case ["quit"]:
return "Quitting application"
case ["load", filename]:
return f"Loading file: {filename}"
case ["save", filename]:
return f"Saving to file: {filename}"
case ["search", *terms]:
return f"Searching for: {', '.join(terms)}"
case _:
return "Unknown command"
print(process_command(["load", "data.txt"]))
print(process_command(["search", "python", "programming"]))
print(process_command(["unknown"]))
Output
Loading file: data.txt Searching for: python, programming Unknown command
Pattern Matching with Conditions
Patterns can include guard conditions using `if` to refine matches. This makes `match` more expressive than simple equality checks.
Example
# Pattern matching with conditions
def check_point(point):
match point:
case (x, y) if x == y:
return f"Point on diagonal: ({x}, {y})"
case (x, y) if x > 0 and y > 0:
return f"Point in first quadrant: ({x}, {y})"
case (x, y):
return f"Point at: ({x}, {y})"
print(check_point((3, 3)))
print(check_point((2, 5)))
print(check_point((-1, 4)))
Output
Point on diagonal: (3, 3) Point in first quadrant: (2, 5) Point at: (-1, 4)