Sub topic 14
Choosing match or if/elif
This chapter assumes you have read the earlier chapters on literal, sequence, mapping and class patterns, guards, and the pitfalls of bare names. It gives you a way to decide which tool fits a given problem. It adds no new syntax.
What each tool is good at
An if/elif chain evaluates arbitrary boolean expressions. A match statement tests the shape of one subject value and binds names to its parts in the same step. Both run the first branch that succeeds, so the difference is what each branch can ask.
| Question about the data | Better fit |
|---|---|
| Is a number in a range, or is `a > b`? | `if`/`elif` |
| Do several unrelated variables satisfy a condition? | `if`/`elif` |
| Is it one of a few constant values? | Either |
| Is it a list or tuple of a certain length, and what are its parts? | `match` |
| Is it a dict with certain keys, and what are their values? | `match` |
| Is it an instance of one of several classes, and what are its attributes? | `match` |
Where if/elif is the better choice
Range checks and comparisons between variables are awkward in match. Each case would need a capture plus a guard, which is longer than the plain conditional.
def grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
return "C"
print(grade(85)) # BThe match version would be case s if s >= 90: repeated for every branch. That adds a name and a keyword without adding any structure to test. Use if here.
Where match is the better choice
Use match when a branch has to check shape and extract parts together. Here is a message handler for dictionaries.
def describe(msg):
match msg:
case {"type": "move", "to": (x, y)}:
return f"move to {x},{y}"
case {"type": "say", "text": str(text)}:
return f"say {text}"
case _:
return "ignored"
print(describe({"type": "move", "to": (3, 4)})) # move to 3,4
print(describe({"type": "say", "text": "hi"})) # say hi
print(describe({"type": "say", "text": 5})) # ignoredThe first case checks that msg is a mapping, that "type" equals "move", that "to" exists, and that its value has exactly two elements. It also binds x and y. With if, you would write an isinstance call, a key lookup, a length check and an unpacking step. A missed check there raises a KeyError or TypeError. A pattern that fails to match simply moves on to the next case.
A decision path
Other things to weigh
- Python version.
matchneeds Python 3.10 or later. A library that supports older versions cannot use it. - Readability for your team. Patterns are compact, so a reader who has not learned them may find a dense case hard to follow. Keep patterns short and move complex conditions into helper functions.
- Silent captures. A bare name in a case captures instead of comparing. In
if/elif, comparing with==is explicit and hard to get wrong. - No fall-through. Unlike a C
switch, only one case runs, so you never needbreak. - Default branch. Without a final
case _, an unmatched subject does nothing. Anifchain withoutelsebehaves the same way. Add a default when silence would hide a bug.
Exercise
You are writing a function that returns "small" for numbers below 10, "medium" for numbers from 10 to 99, and "large" otherwise. Should you use match or if/elif, and why?
Show answer
Use if/elif. The branches are range comparisons on a single number, not tests of shape or type. A match statement would need a guard on every case, such as case n if n < 10:, which is longer and gives no benefit over if n < 10:.