match Statement
Choose between many patterns with structural matching.
Syntax
match value:
case pattern:
...The match statement (added in Python 3.10) compares a value against several case patterns. It is a clean alternative to a long if...elif chain.
Key parts
- Each
caselists a pattern to match. - The underscore
_is a catch-all default. - Matching stops at the first case that fits — no
breakneeded.
Example
day = 3
match day:
case 1:
print('Monday')
case 3:
print('Wednesday')
case _:
print('Another day')
# Output:
# WednesdayWhen to use it
- A CLI dispatcher uses match/case to route commands like 'start', 'stop', and 'status' to handler functions.
- An HTTP router matches the request method string to call the correct GET, POST, or PUT handler.
- A shape renderer uses structural pattern matching to dispatch on the type and fields of a shape object.
More examples
match a string command
Routes a command string to the correct case branch; the wildcard _ handles anything else.
command = 'quit'
match command:
case 'start':
print('Starting...')
case 'stop':
print('Stopping...')
case 'quit':
print('Exiting application')
case _:
print('Unknown command')
# Output:
# Exiting applicationmatch with guard condition
Uses OR patterns and guard clauses (if) to match HTTP status codes by range.
status_code = 404
match status_code:
case 200 | 201:
print('Success')
case code if 400 <= code < 500:
print(f'Client error: {code}')
case code if code >= 500:
print(f'Server error: {code}')
# Output:
# Client error: 404Structural pattern matching on a dict
Matches a dict by its shape and extracts values into variables in one step.
event = {'type': 'click', 'x': 100, 'y': 200}
match event:
case {'type': 'click', 'x': x, 'y': y}:
print(f'Click at ({x}, {y})')
case {'type': 'keypress', 'key': k}:
print(f'Key pressed: {k}')
# Output:
# Click at (100, 200)
Discussion