Python Match
Python · Control Flow
Theory
The match statement, added in Python 3.10, compares one value against a series of case patterns from top to bottom and runs the block of the first pattern that matches; later cases are skipped. case 200: matches the literal 200, and case _: is the wildcard that matches anything, acting like a default or else branch. If no case matches and there is no wildcard, nothing happens and no error is raised.
match is more than a switch: it does structural pattern matching. case 401 | 403: matches either value, case (x, y): unpacks a two-item tuple into x and y, case {'status': s}: pulls a value out of a dict, and a guard like case n if n >= 500: adds a condition. One important trap: a bare name in a case is a capture pattern, not a comparison. case code: matches every value and stores it in code; to compare against a constant, use a literal or a dotted name such as Status.OK. Interpreters older than 3.10 need if/elif instead.
Why we use it
Code that branches on the shape or exact value of data, such as status codes, commands or parsed JSON messages, becomes a long if/elif ladder. match states each case clearly and can unpack values as it matches.
When to use it
Use match for many distinct literal values or when you need to destructure tuples, lists or dicts. For two or three simple conditions, or ranges like salary > 80000, if/elif is simpler. On Python versions before 3.10, use if/elif or a dict lookup.
How it works
- match status_code:
- Does it match case 200? Yes: Run that block: print('OK'). No: Try the next case.
- Does it match case 404? Yes: Run that block. No: Fall through to case _.
- case _ matches anything: print('Error')
- Only the first matching case runs; continue after match
Syntax
match value:
case pattern1:
...
case _:
...Example
match status_code:
case 200:
print('OK')
case _:
print('Error')Key points
- case _ acts as the default/wildcard case
- Only the first matching case runs; there is no fall-through
- case 401 | 403: matches several values
- Supports pattern destructuring of tuples, lists, dicts and objects
- A bare name (case code:) captures any value instead of comparing
- Requires Python 3.10+; use if/elif on older interpreters