Sub topic 15
When to use match instead of elif
This chapter assumes you can write if, elif, and else chains, use comparison and logical operators, and read short function definitions. You also need Python 3.10 or later, because match does not exist in earlier versions. Check your version with python --version.
What match does
A match statement evaluates one expression, called the subject. It then compares the subject against a series of patterns, from top to bottom. The first pattern that fits decides which block runs, and the remaining cases are skipped.
Here is a status-code function written first as an elif chain and then as a match statement.
def describe_elif(status):
if status == 200:
return 'OK'
elif status == 404:
return 'Not Found'
else:
return 'Other'
def describe_match(status):
match status:
case 200:
return 'OK'
case 404:
return 'Not Found'
case _:
return 'Other'
print(describe_elif(404))
print(describe_match(404))Both functions print Not Found. Three details matter:
- The subject (
status) is written once and evaluated once. In theelifversion you repeat it in every condition. case _is the wildcard. It matches anything and plays the role ofelse.- There is no fall-through. Unlike
switchin C or Java, Python runs only the matching block, so you never writebreak.
If no case matches and there is no wildcard, nothing happens and no error is raised. An elif chain without an else behaves the same way.
Matching several values with |
The | operator inside a pattern means "or". It replaces the in test or the repeated == comparisons you would write in an elif condition.
def describe(status):
match status:
case 200 | 201 | 204:
return 'Success'
case 301 | 302:
return 'Redirect'
case 404:
return 'Not Found'
case _:
return 'Other'
print(describe(201))
print(describe(302))
print(describe(500))The output is Success, Redirect, and Other. This is the case where match reads best. You are comparing one value against several constants, which is the pattern from the Topic Spine.
The biggest gotcha: bare names capture
In a pattern, a plain name such as NOT_FOUND is not a lookup of a variable. It is a capture pattern. It matches anything and binds the subject to that name.
NOT_FOUND = 404
def describe(status):
match status:
case NOT_FOUND:
return 'Not Found'
print(describe(200))This prints Not Found for a status of 200. The pattern NOT_FOUND matched any value and rebound the local name to 200. Python rejects code like this only when a later case becomes unreachable. If you add case _: after it, you get a SyntaxError.
There are two safe ways to compare against a named constant:
- Use a dotted name such as
Status.NOT_FOUND. Dotted names are value patterns, and Python compares them with==. - Use a literal, such as
404.
from enum import Enum
class Status(Enum):
OK = 200
NOT_FOUND = 404
def describe(status):
match status:
case Status.OK:
return 'OK'
case Status.NOT_FOUND:
return 'Not Found'
case _:
return 'Other'
print(describe(Status.NOT_FOUND))
print(describe(404))The first call prints Not Found. The second prints Other, because the integer 404 is not equal to the enum member Status.NOT_FOUND. Match the same type you pass in.
Where match is stronger: structure
The main reason to choose match is that patterns can describe the shape of data and pull out parts of it at the same time. Doing this with elif takes several conditions plus indexing.
Sequence patterns
def run(command):
match command.split():
case ['go', direction]:
return f'going {direction}'
case ['pick', 'up', *items]:
return 'picking up ' + ', '.join(items)
case ['quit']:
return 'bye'
case _:
return 'unknown command'
print(run('go north'))
print(run('pick up lamp key'))
print(run('dance'))The output is going north, picking up lamp, key, and unknown command. Each pattern checks the length and the literal words, and it binds direction or items for you. The elif equivalent would test len(parts) == 2 and parts[0] == 'go' and then index into parts.
Sequence patterns match lists and tuples, but not strings or bytes. A string subject will not be unpacked character by character.
Mapping patterns and guards
A mapping pattern checks that certain keys exist and binds their values. Extra keys in the subject are ignored. A guard is an if placed after a pattern. The case matches only when the pattern fits and the guard is true.
def handle(event):
match event:
case {'type': 'click', 'x': x, 'y': y} if x >= 0 and y >= 0:
return f'click at {x},{y}'
case {'type': 'key', 'key': key}:
return f'key {key}'
case _:
return 'ignored'
print(handle({'type': 'click', 'x': 3, 'y': 4}))
print(handle({'type': 'click', 'x': -1, 'y': 4}))
print(handle({'type': 'key', 'key': 'a', 'repeat': True}))The three results are click at 3,4, ignored, and key a. The second event fits the first pattern, but the guard fails. Python then moves on to the next case, and nothing else matches until the wildcard. Without a guard you would need to check for the keys with in and then read them with event['x'].
Class patterns, such as case Point(x=0, y=0):, work the same way for objects and dataclasses. They are most useful when you handle many different object types.
Where elif is still the better choice
match compares structure and equality. It is not a general replacement for conditions. Prefer elif in these situations:
- You test ranges. The grade example (
score >= 90) needs comparisons, and amatchwould need a guard on every case. - The conditions involve different variables, such as
if user.is_adminfollowed byelif disk_full. Amatchhas a single subject. - You combine tests with
andandoron unrelated values. - You must support Python 3.9 or earlier.
- You have only two or three simple branches. An
if/elseis shorter and familiar to every reader.
| Situation | Better choice |
|---|---|
| One value compared to several constants | `match` |
| Unpacking lists, tuples, or dicts by shape | `match` |
| Branching on object type and attributes | `match` |
| Numeric ranges and thresholds | `elif` |
| Tests on several unrelated variables | `elif` |
| Two simple branches | `if`/`else` |
| Code that must run on Python 3.9 or earlier | `elif` |
Common mistakes
- Using a bare name as a constant. As shown above, it captures instead of comparing.
- Putting
case _before other cases. The wildcard matches everything, so later cases never run. Python reports this as aSyntaxErrorfor irrefutable patterns that are not last. - Expecting fall-through. Only the first matching case runs. To share a block, join patterns with
|. - Forgetting that patterns match by type as well as value.
case 1matches1and also1.0andTrue, because==treats them as equal. Check forboolexplicitly if that matters. - Reusing a capture name in an or-pattern. Every alternative in
a | bmust bind the same names. - Overusing match. If each case is a different kind of condition, an
elifchain is clearer.
Exercise
What does this code print, and why? status = 500 match status: case 200 | 201: print('ok') case 500 | 503: print('server error') case _: print('other')
Show answer
It prints "server error". The subject 500 does not match 200 or 201, so the first case is skipped. It does match the second case through the 500 alternative, so that block runs. Python then leaves the match statement without checking case _, because there is no fall-through.
Exercise
A teammate writes case MAX_RETRIES: hoping to match when code equals the constant MAX_RETRIES = 3. What actually happens, and how do you fix it?
Show answer
The bare name is a capture pattern. It matches any value and rebinds MAX_RETRIES to the subject, so the case always runs. Fix it by using the literal case 3: or by moving the constant into a class or enum and writing a dotted name such as case Limits.MAX_RETRIES:.
Exercise
Rewrite the grade logic (90 and up is 'A', 80 and up is 'B', otherwise 'F') using match. Is match a good fit here?
Show answer
One version is match score: with case s if s >= 90: grade = 'A', then case s if s >= 80: grade = 'B', then case _: grade = 'F'. It works, but every case needs a guard, so match adds noise and no benefit. A plain elif chain is the better choice for range tests.