Control Flow: Structural Pattern Matching (match-case in Python 3.10+)
1Concept
Python 3.10 introduced structural pattern matching via match-case, supporting literal matching, sequence unpacking, mapping patterns, and guarded case conditions.
2Architecture Diagram
match command.split():
case ["quit"]: ...
case ["load", filename]: ...
case ["move", x, y] if int(x) > 0: ...3Code Example
Stage 0 Language Foundations
def route_action(event: dict):
match event:
case {"type": "CLICK", "x": x, "y": y} if x > 0 and y > 0:
return f"Valid Click at coordinates ({x}, {y})"
case {"type": "KEYPRESS", "key": ("ENTER" | "RETURN")}:
return "Form submitted via Enter key"
case {"type": "LOGOUT"}:
return "User logged out"
case _:
return "Unhandled event"
print(route_action({"type": "CLICK", "x": 120, "y": 450}))
print(route_action({"type": "KEYPRESS", "key": "ENTER"}))
print(route_action({"type": "SCROLL"}))4Expected Output
Valid Click at coordinates (120, 450) Form submitted via Enter key Unhandled event
5Key Takeaways
- ✓match-case unpacks nested dictionaries and lists natively without manual indexing.
- ✓Guard clauses (case ... if condition) add powerful validation filters.
- ✓case _ serves as the catch-all wildcard.