Sub topic 14
Choosing match or if/elif
This chapter assumes you run Python 3.10 or later. It also assumes you have read the earlier chapters on literal, capture, sequence, mapping, and class patterns, guards, and how cases are tried from top to bottom. Nothing new is introduced here. The chapter gives you criteria for deciding when a match statement improves a piece of code and when an if/elif chain is the better tool.
The short rule
Use match when the decision depends on the shape of a value: its type, its length, which keys it has, or which attributes it has. Use if/elif when the decision depends on arbitrary conditions: comparisons, ranges, boolean combinations, or unrelated variables.
A match statement has one subject, and every case tests that subject. An if/elif chain has no such limit, because each branch can test anything. This one difference explains most of the guidance below.
Where match is clearer
Checking shape and extracting parts together
The strongest case for match is when you must check a structure and pull values out of it. An if/elif version has to test the length, test the content, and index into the data by hand.
def run_if(command):
parts = command.split()
if len(parts) == 1 and parts[0] == "quit":
return "quit"
elif len(parts) == 2 and parts[0] == "go":
return f"go {parts[1]}"
elif len(parts) >= 1 and parts[0] == "drop":
return f"drop {len(parts) - 1} items"
else:
return "unknown command"
def run_match(command):
match command.split():
case ["quit"]:
return "quit"
case ["go", direction]:
return f"go {direction}"
case ["drop", *items]:
return f"drop {len(items)} items"
case _:
return "unknown command"
for text in ["quit", "go north", "drop a b c", "dance"]:
assert run_if(text) == run_match(text)
print(run_match(text))The two functions behave the same. In the match version, the length checks are implicit in the pattern, and direction and items are bound for you. There are no magic indexes such as parts[1], so an off-by-one error in the length test is much less likely.
Nested data and several types
Data from JSON, parsed syntax trees, and message protocols is nested. A single mapping pattern can test several keys and a nested tuple at once. Doing the same with if needs isinstance, in, and indexing in every branch. Class patterns give the same benefit for small hierarchies of dataclasses:
from dataclasses import dataclass
@dataclass
class Circle:
radius: float
@dataclass
class Rect:
width: float
height: float
def area(shape):
match shape:
case Circle(radius=r):
return 3.14159 * r ** 2
case Rect(width=w, height=h):
return w * h
case _:
raise TypeError(f"unknown shape: {shape!r}")
print(area(Rect(3, 4))) # 12An isinstance chain would work here too. The gain from match is modest with two types and grows as patterns nest deeper.
Where if/elif is better
Ranges and comparisons
Patterns test equality and structure. They do not test "greater than." To express a range in match, you must capture the value and add a guard to every case:
def grade_match(score):
match score:
case s if s >= 90:
return "A"
case s if s >= 80:
return "B"
case s if s >= 70:
return "C"
case _:
return "F"
def grade_if(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
else:
return "F"
print(grade_if(85), grade_match(85)) # B BThe match version repeats case s if on every line and gains nothing from the pattern. When most of your cases need a guard, the patterns are not doing any work, and if/elif is the honest choice.
Unrelated conditions
If the branches test different variables, there is no single subject to match against. Code such as if user.is_admin or request.method == "GET": is a boolean expression and has no pattern form.
Two branches, and older Python
For a single yes/no decision, if/else is shorter and more familiar to readers. Also, match is a syntax error before Python 3.10. A library that supports 3.9 or earlier cannot use it.
Summary table
| Situation | Prefer | Reason |
|---|---|---|
| Parsing a list of tokens by length and content | `match` | Sequence patterns check length and bind elements in one step |
| Handling dictionaries with different keys | `match` | Mapping patterns test keys and nested values together |
| Handling several dataclass types | `match` | Class patterns test type and attributes together |
| Numeric ranges such as grade bands | `if`/`elif` | Patterns cannot express `>=` without a guard on every case |
| Conditions on several unrelated variables | `if`/`elif` | `match` has only one subject |
| Mapping a value to a constant result | dict lookup | `{"red": "#f00"}.get(name)` is shorter than any branching |
| Behavior that belongs to a type | method | Polymorphism keeps the logic next to the data |
| Code that must run on Python 3.9 | `if`/`elif` | `match` is a syntax error there |
Edge cases that affect the choice
No match is not an error
If no case matches and there is no case _, the match statement does nothing and execution continues. A function then returns None without any warning:
def sign(n):
match n:
case 0:
return "zero"
print(sign(5)) # NoneAn if/elif chain without else has the same behavior, so this is not a reason to prefer one over the other. It does mean that you should end a match with case _: raise ... whenever an unexpected value is a bug.
Checking exhaustiveness with a type checker
Static type checkers such as mypy and pyright can verify that a match handles every member of an enum or every type in a union. You enable this by calling assert_never in the final case. This check is a real advantage of match, because a checker cannot do the same for an elif chain as easily. typing.assert_never is available from Python 3.11. On 3.10, import it from typing_extensions.
from enum import Enum
from typing import assert_never
class Mode(Enum):
READ = "r"
WRITE = "w"
def label(mode: Mode) -> str:
match mode:
case Mode.READ:
return "read-only"
case Mode.WRITE:
return "writable"
case _:
assert_never(mode)
print(label(Mode.WRITE)) # writableIf you later add APPEND to Mode and forget this function, the type checker reports an error at the assert_never line. At runtime, the same mistake raises an AssertionError when the new member reaches that line.
Literal matching uses equality, with exceptions
Most literal patterns compare with ==, so case 1 also matches True and 1.0, because True == 1 and 1.0 == 1. The singletons None, True, and False are compared with is. If your subject can hold booleans and integers, check the order of your cases. Careful if code often uses is True or isinstance for this reason.
Performance is not a reason to choose match
CPython does not compile match into a jump table. It tests the cases one after another, much like an if chain. Choose between them for readability. If a long chain is a bottleneck, a dictionary lookup is usually faster than either.
Mutable state and side effects
A pattern can call code you did not expect. Class patterns use isinstance and attribute access, which may run properties. A guard can run any expression. Keep guards free of side effects. Cases are tried in order, so the number of times a guard runs depends on the order of the cases above it.
A practical checklist
Work through these questions when you are unsure:
- Is there one subject that every branch inspects? If not, use
if/elif. - Do the branches test shape (type, length, keys, attributes) rather than ranges? If yes, lean toward
match. - Do more than about half of the cases need a guard? If yes, switch to
if/elif. - Does the code need to run on Python older than 3.10? If yes, avoid
match. - Are you only turning a value into another value? Try a dictionary first.
- Is an unexpected value a bug? Add a final
case _that raises, or useassert_neverwith a type checker.
Exercises
Exercise
A function receives a dict such as {"op": "add", "args": [1, 2]} or {"op": "neg", "args": [5]} and must check both the operation name and the number of arguments. Would you use match or if/elif, and why?
Show answer
Use match. A mapping pattern with a nested sequence pattern, such as case {"op": "add", "args": [a, b]}, checks the key, the value, and the list length in one step and binds a and b. The if/elif version would need an "op" test, a len() test, and indexing in every branch.
Exercise
A function returns "cheap" for prices below 10, "fair" for prices from 10 up to 50, and "expensive" otherwise. Which construct fits best, and what makes the match version awkward?
Show answer
if/elif fits best. The conditions are numeric ranges, and patterns cannot express "less than." A match version needs a captured name plus a guard on almost every case (case p if p < 10:), which repeats syntax and adds no structural matching.
Exercise
You write match color: case RED: return "red" case _: return "other", where RED is a module-level constant. What happens when color is "blue", and how do you fix it?
Show answer
The bare name RED is a capture pattern, so it matches any value, binds it to RED, and returns "red" for "blue" too. Use a value pattern with a dotted name, such as Color.RED where Color is an enum or class, or use a literal pattern like "red".