Structural Pattern Matching (match-case / PEP 634)
1Concept
Python 3.10 introduced Structural Pattern Matching with `match` and `case`. It allows matching on values, destructuring sequences (`[x, y, *rest]`), mappings (`{'status': s}`), and class instances (`Point(x, y)`), with guard clauses (`if condition`).
2Architecture Diagram
match command.split():
case ["go", ("north" | "south" | "east" | "west") as direction]:
case ["get", item]:
case _:3Code Example
Python 3.12
def process_api_response(response):
match response:
case {"status": 200, "data": list() as items} if len(items) > 0:
return f"Success: Processed {len(items)} items"
case {"status": 200, "data": []}:
return "Warning: Empty dataset returned"
case {"status": 404, "error": message}:
return f"Not Found Error: {message}"
case {"status": code}:
return f"HTTP Status Code: {code}"
case _:
return "Malformed Response Payload"
print(process_api_response({"status": 200, "data": ["User1", "User2"]}))
print(process_api_response({"status": 404, "error": "User ID missing"}))4Expected Output
Success: Processed 2 items Not Found Error: User ID missing
5Key Takeaways
- ✓`_` serves as the wildcard pattern matching anything without binding variable names.
- ✓Guard clauses (`if condition`) run only after the pattern structure successfully matches.
- ✓Mapping patterns match even if the dictionary contains additional extra keys.