capypad
0 day streak
python / expert
Snippet

Advanced Pattern Matching with Guards

Structural Pattern Matching (introduced in Python 3.10) allows for expressive data deconstruction. Using 'guards' (the 'if' clause after a pattern) enables adding conditional logic directly into the matching process, allowing for more granular control over complex dictionary or object structures.

snippet.py
python
1
2
3
4
5
6
7
8
def process_data(payload):
match payload:
case {"type": "user", "id": int(uid)} if uid > 1000:
return f"Admin logic for {uid}"
case {"type": "user", "id": int(uid)}:
return f"User logic for {uid}"
case _:
raise ValueError("Unknown format")
Breakdown
1
match payload:
Starts the pattern matching block against the payload variable.
2
case {"type": "user", "id": int(uid)} if uid > 1000:
Matches a dict structure, captures 'uid', and applies a conditional guard.
3
case _:
The wildcard pattern that matches anything not caught by previous cases.