When you need to pick one of many actions based on a single value, an
if/elif chain works but gets noisy fast. Python 3.10 added the match statement: each choice gets its own case line, so it is easier to scan.Literal patterns
command = 'quit'
match command:
case 'go':
print('moving')
case 'look':
print('describing room')
case 'quit' | 'exit': # '|' means "or"
print('bye')
case _:
print('unknown command')case lines test the value that follows match. The first case that matches runs, and the match stops there: later cases are skipped, even if they would match too. _ is a wildcard that catches anything not matched earlier.Capturing values with sequence patterns
# .split() cuts text into a list of words
words = 'drop sword shield'.split()
match words:
# an empty list
case []:
print('nothing typed')
# 'drop' plus any number of items
case ['drop', *items]:
print('dropping:', items)
# exactly one word, captured as verb
case [verb]:
print(f'verb is {verb}')
# exactly two words
case [verb, direction]:
print(f'{verb} toward {direction}')* is a star pattern: it grabs zero or more remaining elements into a list. Patterns run top to bottom, so the specific 'drop' case comes before the general two-word case: otherwise drop sword would be caught as a verb and a direction.Mapping patterns and guards
event = {'type': 'move', 'x': 3, 'y': -1}
match event:
# a shape plus a guard
case {'type': 'move', 'x': x, 'y': y} if x > 0:
print(f'move right to ({x},{y})')
case {'type': 'move', 'x': x, 'y': y}:
print(f'move to ({x},{y})')
# any other dictionary with a 'type' key
case {'type': t}:
print('got type:', t)
case _:
print('not an event')if after a pattern is a guard: the case only matches when both the shape and the condition are true. This keeps the condition on the case line, instead of in an extra if inside the case. A guard can check a type too: isinstance(x, int) is True when x is a whole number (an int).A mapping pattern matches any dictionary that has at least those keys: extra keys are fine. That is why the general
{'type': t} case has to come last.