Topic 12 of 58
match / case
Overview
Introduced in Python 3.10, match and case bring Structural Pattern Matching to Python. While it looks similar to a switch statement in C or JavaScript, it is vastly more powerful. It doesn't just compare basic values; it can 'unpack' data structures, match specific shapes of lists or dictionaries, and bind variables on the fly, making complex data parsing incredibly elegant.
Syntax
python
def analyze_http_response(status_code):
match status_code:
case 200:
return "OK"
case 400 | 401 | 403 | 404: # Combine multiple matches with pipe
return "Client Error"
case 500:
return "Server Error"
case _: # Wildcard (Default case)
return "Unknown Status Code"
print(analyze_http_response(404)) # Client ErrorCommon Pitfalls
- Attempting to use
matchin Python 3.9 or older; it will immediately throw a SyntaxError. - Forgetting the wildcard
case _:at the end. If no cases match and there is no wildcard, the block silently does nothing and returns None.
Interview Questions
Q:
What makes structural pattern matching more powerful than a traditional switch statement?
A:
It can match the 'shape' of data. You can match against a list of exactly two elements, extract those elements into variables instantly, and even apply 'guard' clauses (case [x, y] if x == y:).
Real-World Example
Parsing complex JSON-like event data dynamically.
example
python
def process_event(event):
match event:
# Matches a dict with specific keys, and extracts 'x' and 'y'
case {"type": "click", "loc": (x, y)}:
print(f"User clicked at coordinates {x}, {y}")
# Matches and extracts the key name
case {"type": "keypress", "key": key_name}:
print(f"User pressed the {key_name} key")
case _:
print("Unrecognized event payload")
process_event({"type": "click", "loc": (150, 200)})Check Your Knowledge
Test your understanding of match / case with these quick questions.