Sub topic 7
Refining a case with if guards
This chapter assumes you know Python 3.10 or later, the basic match and case syntax, capture patterns and the _ wildcard, and that you can read simple sequence, mapping and class patterns. It covers what a guard is, when it runs, which names it can see, and the mistakes that guards cause.
What a guard is
A pattern describes the shape of a value. It cannot express "the number is greater than 10" or "these two fields are equal". A guard adds that kind of condition. It is an if clause placed after the pattern and before the colon:
case <pattern> if <condition>:The case runs only when the pattern matches and the condition is truthy. If the pattern matches but the condition is falsy, Python moves on to the next case, as if the pattern had failed.
def classify(n):
match n:
case int(x) if x < 0:
return "negative"
case 0:
return "zero"
case int(x) if x % 2 == 0:
return "positive even"
case int():
return "positive odd"
case _:
return "not an int"
print(classify(-3)) # negative
print(classify(0)) # zero
print(classify(8)) # positive even
print(classify(7)) # positive odd
print(classify("x")) # not an intint(x) is a class pattern that matches any int and binds the whole value to x. The guard then tests x. The third and fourth cases show the usual shape. A guarded case handles the special situation, and an unguarded case below it handles everything else of the same shape.
The order of events
A guarded case goes through three steps, in this order:
- The pattern is tried against the subject.
- If it matches, its capture names are bound.
- The guard is evaluated, and it can read those names.
The guard is never evaluated when the pattern fails. This lets a guard assume the shape the pattern established. In case [a, b] if a < b, the guard can rely on the subject being a two-element sequence.
Guards on different pattern types
A guard can follow any pattern. It is most useful where the pattern captures values you want to compare.
Sequence patterns
The condition can relate several captured elements to each other, which no pattern can do on its own:
def ratio_label(pair):
match pair:
case [a, b] if b != 0 and a / b > 1:
return "greater than one"
case [a, b] if b != 0:
return "at most one"
case [_, _]:
return "undefined"
case _:
return "not a pair"
print(ratio_label([10, 5])) # greater than one
print(ratio_label([1, 5])) # at most one
print(ratio_label([1, 0])) # undefined
print(ratio_label([1])) # not a pairThe b != 0 and part matters. A guard is ordinary code, so an exception inside it propagates out of the whole match statement. Without that check, [1, 0] would raise ZeroDivisionError instead of falling through.
Mapping patterns
A mapping pattern checks which keys exist. A guard checks what their values are:
def shipping(order):
match order:
case {"country": "US", "total": total} if total >= 50:
return "free shipping"
case {"country": "US"}:
return "flat rate"
case {"country": country, "total": total} if total >= 150:
return f"free international to {country}"
case {"country": _}:
return "international rate"
case _:
return "invalid order"
print(shipping({"country": "US", "total": 60})) # free shipping
print(shipping({"country": "US", "total": 10})) # flat rate
print(shipping({"country": "DE", "total": 200})) # free international to DE
print(shipping({"country": "DE", "total": 20})) # international rate
print(shipping({"total": 20})) # invalid orderEach unguarded case catches whatever the guarded case above it rejected. The second case does not repeat the total condition, because a US order that reached it already failed the first case.
Class patterns
Guards pair well with class patterns when the rule involves more than one attribute:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def region(p):
match p:
case Point(x, y) if x == y == 0:
return "origin"
case Point(x, y) if x == y:
return "diagonal"
case Point(x, y) if x > 0 and y > 0:
return "first quadrant"
case Point():
return "elsewhere"
case _:
return "not a point"
print(region(Point(0, 0))) # origin
print(region(Point(2, 2))) # diagonal
print(region(Point(3, 1))) # first quadrant
print(region(Point(-1, 4))) # elsewhere
print(region("hi")) # not a pointThe positional form Point(x, y) works because @dataclass generates __match_args__. The origin case comes before the diagonal case. Order matters here, because Point(0, 0) satisfies both guards.
Guards and or-patterns
A guard applies to the whole case, not to one alternative. In case "sat" | "sun" if hour < 10, the condition is tested whichever alternative matched:
def door(day, hour):
match day:
case "sat" | "sun" if hour < 10:
return "closed (weekend morning)"
case "sat" | "sun":
return "open (weekend)"
case _:
return "open (weekday)"
print(door("sun", 8)) # closed (weekend morning)
print(door("sat", 14)) # open (weekend)
print(door("mon", 8)) # open (weekday)If you need a different condition per alternative, write separate cases. A single guard cannot depend on which alternative matched.
Comparing against outside variables
A bare name in a pattern captures. It does not compare, so a pattern cannot refer to an existing variable. A guard can, because the guard is an ordinary expression:
LIMIT = 10
def check(n):
match n:
case int(x) if x > LIMIT:
return "over the limit"
case int():
return "within the limit"
case _:
return "not a number"
print(check(25)) # over the limit
print(check(3)) # within the limitWriting case LIMIT: would match every value and rebind LIMIT. For exact equality with a constant, a dotted name such as Config.LIMIT is a value pattern. For anything beyond equality, use a guard.
Gotchas
Names stay bound after a failed guard
Capture names are bound in step 2, before the guard runs. If the guard is falsy, Python moves on, but the bindings are not undone:
match [5, 6]:
case [a, b] if a > b:
print("descending")
case _:
print("something else")
print(a, b) # 5 6The output is something else, then 5 6. Treat names from a failed guarded case as unreliable. Do not read them after the match unless every path that reaches that line is known to have bound them. A name may also silently overwrite a variable that already existed under the same name.
Guards can have side effects
A guard is evaluated every time Python reaches its case, and once per reach. Keep guards free of side effects. A guard that logs, consumes an iterator or updates a counter will do so even when the case does not run. This is also why you should avoid expensive calls in guards that sit near the top of a long match.
Guards are invisible to the pattern
Python does not look inside a guard. It will not warn you that two guarded cases overlap, and a guarded case does not make a later case unreachable. Pattern-only mistakes, such as a capture or _ case placed too early, are covered under evaluation order and pitfalls in later chapters. A guard that is always truthy is simply a case that always runs once its pattern matches.
Long guards
Wrap a long guard in parentheses so it can span lines:
match order:
case {"total": total, "items": items} if (
total > 100
and len(items) > 3
):
print("bulk discount")If a guard needs this much room, consider whether a helper function with a clear name would read better.
Pattern or guard?
| Question | Put it in the pattern | Put it in the guard |
|---|---|---|
| Is the subject a certain type or shape? | Yes | No |
| Does a key or attribute exist? | Yes | No |
| Does a value equal a literal or dotted constant? | Yes | Only if the pattern cannot say it |
| Is a value greater than, less than or in a range? | Not possible | Yes |
| Do two captured values relate to each other? | Not possible | Yes |
| Is a value compared to a local variable? | Not possible | Yes |
Put as much as you can into the pattern and use the guard for the rest. The pattern also states the shape of the data, which makes the case easier to read.
Exercises
Exercise
What does this print, and why? match [3, 9]: case [a, b] if a > b: print("first") case [a, b] if a + b > 10: print("second") case [a, b]: print("third")
Show answer
It prints "second". The first case's pattern matches, but its guard 3 > 9 is falsy, so Python moves on. The second case's pattern matches and its guard 3 + 9 > 10 is truthy, so its body runs and the match ends. The third case is never reached.
Exercise
Write a function bucket(value) that returns "small" for an int from 1 to 9, "large" for an int of 10 or more, and "other" for anything else, including zero, negative ints and non-ints. Use guards and no if statements.
Show answer
def bucket(value): match value: case int(n) if 1 <= n < 10: return "small" case int(n) if n >= 10: return "large" case _: return "other" The class pattern int(n) rejects non-ints before either guard runs. Zero and negative ints match the pattern but fail both guards, so they reach the wildcard. Note that True is an int, so bucket(True) returns "small".