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 event:
case {"type": "user.created", "payload": payload}:
handle_user(payload)
case {"type": "invoice.failed"}:
alert_finance()
case _:
log.warning("Unknown event")
- Patterns can match dictionaries, sequences, literals, class instances.
_acts as a wildcard.
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+.