Sub topic 12
How cases are tried, top to bottom
This chapter assumes you are on Python 3.10 or later. It also assumes you know the basic pattern types from earlier chapters: literal, capture, wildcard, sequence, class patterns, and guards. Here you learn the order in which Python checks them and what that means for the code you write.
The rule: first match wins
Python evaluates the subject expression once. It then tries each case from the top. The first case whose pattern matches, and whose guard (if any) is true, runs its block. The remaining cases are skipped. No case falls through to the next one, so there is no break.
If no case matches and there is no wildcard, the match statement does nothing. It does not raise an error.
Order changes the result
A general pattern placed before a specific one hides the specific one.
def classify(n):
match n:
case int():
return "int"
case 0:
return "zero"
case _:
return "other"
print(classify(0)) # int
print(classify("x")) # otherThe case 0 branch can never run. Every 0 is an int, so the first case already took it. Put specific cases first and general ones last. The _ wildcard and bare capture patterns always match, so they belong at the end.
The subject is evaluated once
The expression after match runs one time, however many cases there are. Each case then tests the same value.
def get():
print("subject evaluated")
return (1, 2)
match get():
case (0, _):
print("first")
case (1, y) if y > 5:
print("guard failed")
case (1, y):
print("y is", y)Output:
subject evaluated
y is 2The second case matched the shape (1, y), so y was bound to 2. Then its guard y > 5 was false, so Python moved on to the third case.
Captures can survive a failed case
Python binds names while it matches a pattern. If the pattern matches but the guard fails, the names stay bound. If a pattern fails halfway through, some names may already be bound. Do not rely on a name from a case that did not run.
Only what a pattern needs is evaluated
Patterns are checked left to right and stop at the first failure. In case [1, 2, x], a list of length 2 fails on length and never binds x. Guards run only after their pattern matches, so an expensive or risky guard is skipped for subjects that do not fit the shape.
A guard is also a good place for a check the pattern cannot express. Keep it free of side effects, because it may run for cases that never end up running their block.
Reading a match from the top
When you review a match, ask these questions in order:
- Could an earlier case match everything a later case matches? If so, the later case is unreachable.
- Is the catch-all (
_) last? - Does any guard depend on a name bound earlier in the same case?
Python rejects some mistakes at compile time. A bare capture or _ before the last case is a SyntaxError, with a message like "wildcard makes remaining patterns unreachable". It cannot catch overlaps such as int() before 0, so those are your job.
Exercise
What does this code print, and why? match [1, 2, 3]: case [1, rest] if len(rest) > 5: print("A") case [1, 2]: print("B") case [items]: print("C", items) case _: print("D")
Show answer
It prints "C [1, 2, 3]". The first case matches the shape with rest = [2, 3], but its guard len(rest) > 5 is false, so Python moves on. The second case needs exactly two elements and fails on length. The third case matches any sequence and captures all three elements. The wildcard is never reached.