Sub topic 15
When to use match instead of elif
This chapter assumes you can write if/elif/else chains, define functions, and compare values with == and in. It also assumes you run Python 3.10 or later, because match does not exist in earlier versions.
The problem with long elif chains
An elif chain that compares one value against several constants repeats the variable name on every line:
def describe(status):
if status == 200:
return 'OK'
elif status == 404:
return 'Not Found'
else:
return 'Other'
print(describe(404))This works, and for two or three cases it is fine. With many cases, the repeated status == adds noise. The match statement states the subject once and lists the cases below it.
The match statement
Here is the same function written with match:
def describe(status):
match status:
case 200:
return 'OK'
case 404:
return 'Not Found'
case _:
return 'Other'
print(describe(404))
print(describe(500))This prints Not Found, then Other. Python evaluates status once and compares it with each case from top to bottom. It runs the first block that matches and skips the rest, just as elif does. The pattern _ is a wildcard that matches anything, so case _: plays the role of else.
Matching several values
Use | to combine patterns in one case:
def category(status):
match status:
case 200 | 201 | 204:
return 'success'
case 301 | 302:
return 'redirect'
case _:
return 'other'
print(category(201))The elif equivalent is status in (200, 201, 204). Both are fine, and match reads slightly better when each group has its own named outcome.
Gotchas
A bare name in a case is not a comparison. It is a capture pattern that matches anything and assigns the value to that name.
A case can have a guard, an if condition after the pattern. The case runs only when the pattern matches and the guard is true:
def sign(n):
match n:
case 0:
return 'zero'
case _ if n > 0:
return 'positive'
case _:
return 'negative'
print(sign(-3))Also remember that match was added in Python 3.10. On older versions, it is a SyntaxError.
Choosing between match and elif
| Situation | Better choice |
|---|---|
| One value compared with several constants | `match` |
| Conditions on different variables | `elif` |
| Range tests such as `score >= 90` | `elif` |
| Code must run on Python older than 3.10 | `elif` |
| Only two or three simple cases | Either, usually `if`/`elif` |
Use match when one subject is tested against many fixed values. Use elif when each branch asks a different question, since match cannot express arbitrary boolean conditions without guards.
Exercise
Rewrite this function using match. What does it return for "stop", and for "jump"? def action(command): if command == 'go': return 'moving' elif command == 'stop': return 'halting' else: return 'unknown'
Show answer
def action(command): match command: case 'go': return 'moving' case 'stop': return 'halting' case : return 'unknown' It returns 'halting' for "stop" and 'unknown' for "jump", because "jump" matches no literal case and falls through to the wildcard ``.
Exercise
Why does case limit: inside a match statement not compare the subject with an existing variable named limit?
Show answer
A bare name is a capture pattern. It matches any value and assigns it to limit. Comparing against a variable needs a guard such as case _ if value == limit: or an ordinary if statement.