Python match-case
Satellite · Control Flow
Structural Pattern Matching
`match-case` brings robust pattern matching to Python. Handle complex payloads and state machines with clarity.
Syntax
match command:
case "quit":
sys.exit()
case "hello":
print("Hello!")
case _:
print(f"Unknown command: {command}")
_is a wildcard that matches anything.
Matching data structures
match event:
case {"type": "user.created", "payload": payload}:
handle_user(payload)
case {"type": "invoice.failed"}:
alert_finance()
case [first, *rest]:
process(first, rest)
- Patterns can match literals, sequences, dictionaries, and class instances.
- Use
*restto capture remaining elements in sequences.
Guards
match payload:
case {"type": "user", "active": True} if payload["tier"] == "pro":
onboard_pro_user(payload)
Guards add Boolean conditions to pattern matches.
Tips
- Order matters; the first matching case executes.
- Keep cases simple; extract handlers for complex logic.
- Requires Python 3.10+.