Sub topic 12
How cases are tried, top to bottom
This chapter explains the order in which a match statement does its work. You should already know the basic match and case syntax, capture and wildcard patterns, and guards. You need Python 3.10 or later.
The algorithm in one pass
A match statement runs in these steps:
- Evaluate the subject expression once.
- Take the first
caseblock and test its pattern against the subject. - If the pattern matches, bind its capture names, then evaluate the guard if there is one.
- If the pattern matched and the guard is true (or absent), run that block and leave the
matchstatement. Nothing else is tried. - Otherwise move to the next
caseand repeat from step 2. - If no case is selected, do nothing and continue after the
match.
The subject is evaluated once
The subject can be any expression, such as a function call. Python evaluates it one time and compares that single value against every pattern.
def next_value():
print("evaluating subject")
return 7
match next_value():
case 1:
print("one")
case 7:
print("seven")
case _:
print("other")This prints evaluating subject once, then seven, even though two cases were tried. You do not need to store the result in a variable first to avoid repeated calls.
First match wins, with no fallthrough
Unlike a C-style switch, a match statement never continues into the next block. You do not write break. If two patterns could both match the subject, only the earlier one runs.
This makes the order of your cases part of the logic. Put specific patterns before general ones.
def describe(point):
match point:
case (0, 0):
return "origin"
case (0, _) | (_, 0):
return "on an axis"
case (x, y):
return f"at {x},{y}"
case _:
return "not a pair"
print(describe((0, 0))) # origin
print(describe((0, 5))) # on an axis
print(describe((3, 4))) # at 3,4
print(describe("ab")) # not a pair
print(describe(5)) # not a pairIf you moved case (x, y) to the top, (0, 0) would be reported as at 0,0 and the two more specific cases could never run. Python does not warn you about this. The code is valid and silently wrong.
The string "ab" falls to the last case because sequence patterns never match str, bytes, or bytearray, even though those types are sequences.
When no case matches
If no case matches and none is a wildcard, the match statement does nothing. There is no exception and no return value.
def label(n):
match n:
case 1:
return "one"
case 2:
return "two"
print(label(3)) # NoneThe function falls off its end and returns None. If a missing case is a bug in your program, end the statement with an explicit failure:
def label(n):
match n:
case 1:
return "one"
case 2:
return "two"
case _:
raise ValueError(f"unexpected value: {n!r}")Irrefutable patterns must come last
A pattern that matches every subject is called irrefutable. The wildcard _ and a bare capture name such as x are irrefutable. Any case after one could never run, so Python rejects it at compile time.
source = """
match 1:
case x:
print(x)
case 2:
print("two")
"""
try:
compile(source, "<demo>", "exec")
except SyntaxError as error:
print(error.msg)This prints a message saying that the name capture x makes the remaining patterns unreachable. The same rule applies to _.
Two details are worth remembering:
- Only an irrefutable pattern with no guard triggers the error.
case x if x > 3:can fail, so it may appear before other cases. - Python can only detect this for patterns that always succeed. It cannot detect that
case int()shadows a latercase 0. That mistake is yours to find.
Order of work inside one case
Within a single case, Python tests in a fixed order:
| Step | What happens | Can it stop the case? |
|---|---|---|
| 1 | The pattern is checked against the subject. Sub-patterns are tried left to right. | Yes, if any part fails. |
| 2 | Capture names are bound. | No. |
| 3 | The guard after `if` is evaluated. | Yes, if it is false. |
An or-pattern such as 1 | 2 | 3 tries its alternatives from left to right and stops at the first one that matches. A guard is evaluated only after its pattern has matched. That is why guards can safely use captured names:
def check(n):
print(f"guard sees {n}")
return n > 10
match 5:
case n if check(n):
print("big")
case n if n > 3:
print("medium")
case _:
print("small")The output is guard sees 5 followed by medium. The first case matched its pattern, bound n, and ran its guard. The guard returned False, so Python moved on. The second case then bound n again and its guard passed.
You can see the leftover bindings after a guard fails:
pair = (1, 99)
match pair:
case (x, y) if y < 10:
print("small y")
case _:
print("fallback")
print(x, y) # 1 99The first case did not run, but x and y still hold the values it captured. In the same way, if a pattern such as case (x, "no") fails on its second element, the language does not promise whether x was bound. Do not read a name in a later case or after the match unless every path through the statement binds it.
Side effects and how many times things run
Matching can run Python code you did not write on the case line:
- A value pattern such as
Color.REDlooks up an attribute. - A class pattern calls
isinstanceand reads attributes, which may be properties. - A mapping pattern looks up keys with the mapping's
getmethod, so it does not insert missing keys into adefaultdict. - A guard runs any expression you write.
The language reference allows an implementation to cache or skip repeated checks, for example evaluating the same attribute once when two cases both use it. So write patterns and guards that are cheap and free of side effects. Put side effects inside the selected block, where they run exactly once.
Ordering for speed and clarity
Because Python tries cases one after another, the cost of a match grows with the number of cases it must test before one is selected. For a handful of cases this is irrelevant. For a long list, put the most common cases first, as long as that does not break the specific-before-general rule.
Cheap, broad checks before expensive ones also help. A literal comparison is cheaper than a class pattern with many attributes. If a guard calls a slow function, make sure the pattern has already ruled out most subjects.
def handle(event):
match event:
case {"type": "ping"}:
return "pong"
case {"type": "upload", "size": size} if size > 10_000_000:
return "rejected: too large"
case {"type": "upload", "name": name}:
return f"stored {name}"
case _:
return "ignored"
print(handle({"type": "upload", "name": "a.txt", "size": 20_000_000})) # rejected: too large
print(handle({"type": "upload", "name": "a.txt", "size": 5})) # stored a.txt
print(handle({"type": "ping"})) # pongThe large-upload case comes before the general upload case. Reversed, no upload would ever be rejected, because the general case would always be selected first.
Common ordering mistakes
- A general class pattern such as
case Shape():placed beforecase Circle():. The subclass case never runs. - A bare name used as a "constant" earlier in the list. It captures and shadows everything after it, which the compiler reports as a
SyntaxError. - A broad sequence pattern like
[first, *rest]placed before a precise one like[]or["quit"]. - A guard with a side effect, for example one that appends to a list. It can run for several cases before one is selected.
- Reading a captured name after a
matchin which a different case ran.
Exercise
Predict the output of the following code, and explain which case is selected and why. def f(value): match value: case [x, rest] if len(rest) > 1: return "long" case [x, y]: return "pair" case [x, rest]: return "some" case _: return "other" print(f([1, 2]), f([1, 2, 3]), f([1]), f("ab"))
Show answer
It prints "pair long some other". For [1, 2], the first case matches the pattern but rest is [2], so the guard len(rest) > 1 is false and Python moves on. The second case matches exactly two elements. For [1, 2, 3], rest is [2, 3], the guard is true, so the first case runs. For [1], the first case fails the guard (rest is empty), the second fails on length, and the third matches. The string "ab" matches no sequence pattern because str is excluded, so the wildcard selects "other".
Exercise
This function should return "zero" for 0 and "positive int" for other ints, but it never returns "zero". Fix it by changing the order of cases, and explain why the original fails. def kind(n): match n: case int(): return "positive int" case 0: return "zero" case _: return "other"
Show answer
Put case 0 before case int(). The original selects case int() for 0 because 0 is an int, and the first matching case wins, so case 0 is unreachable. Python does not report an error for this because int() is not irrefutable (it fails for non-ints). The fixed version tries the specific literal first: case 0 returns "zero", then case int() handles every other int, and case _ handles everything else. Note that the function still labels negative ints "positive int", which is a separate bug that would need its own guard-based cases.