Sub topic 7
Refining a case with if guards
This chapter assumes you have Python 3.10 or later and know capture patterns, the _ wildcard, and sequence and class patterns from earlier chapters. A pattern checks the shape of a value. It cannot express every condition, such as "the number is positive" or "the two coordinates are equal". A guard adds that kind of condition.
What a guard is
A guard is an if clause after a pattern:
def sign(value):
match value:
case int() if value < 0:
return "negative"
case int() if value == 0:
return "zero"
case int():
return "positive"
case _:
return "not an integer"
print(sign(-4)) # negative
print(sign(0)) # zero
print(sign(7)) # positive
print(sign("x")) # not an integerA case succeeds only when the pattern matches and the guard expression is truthy. If the pattern matches but the guard is falsy, Python moves on to the next case.
The order of checks
The pattern is tested first. The guard runs only after the pattern has matched, so it can use any names the pattern captured.
This order is why guards are safe in many situations. A guard can rely on the structure the pattern has already confirmed.
Guards that use captured names
Guards are most useful with captures. The pattern extracts the parts, and the guard checks them.
def run(command):
match command.split():
case ["go", direction] if direction in {"north", "south", "east", "west"}:
return f"go {direction}"
case ["go", _]:
return "bad direction"
case _:
return "unknown command"
print(run("go north")) # go north
print(run("go up")) # bad direction
print(run("dance")) # unknown commandHere ["go", direction] matches any two-word command that starts with go. The guard rejects directions that are not allowed. The second case catches those rejected commands.
The same technique works with class patterns:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def where(p):
match p:
case Point(x, y) if x == y:
return "on the diagonal"
case Point():
return "elsewhere"
print(where(Point(2, 2))) # on the diagonal
print(where(Point(1, 3))) # elsewhereCommon errors
- Ordering a guarded case after a general one. A case without a guard matches everything its pattern allows. If it comes first, later guarded cases for the same shape never run. Put guarded cases before the general case.
- Expecting bindings to be undone. Names captured by a pattern stay bound even if the guard fails.
- Side effects in guards. A guard can run for several cases before one succeeds. Calling a function that changes state, or reads input, makes the result depend on how many cases were tried.
- Using a guard where a pattern would do.
case x if x == 200works, butcase 200is shorter and states the intent directly.
You can see this directly:
match [1, 2]:
case [a, b] if a > b:
print("descending")
case _:
print(a, b) # 1 2The first guard is false, so the wildcard case runs. It prints 1 2 because the first pattern had already bound both names.
Guards with or-patterns
A guard applies to the whole case, including every alternative in an or-pattern. The guard is checked once, after one alternative has matched.
def classify(code):
match code:
case 301 | 302 | 307 if code != 307:
return "classic redirect"
case 301 | 302 | 307:
return "other redirect"
case _:
return "not a redirect"
print(classify(302)) # classic redirect
print(classify(307)) # other redirectExercise
A function contains case [x, y] if x > y: followed by case [x, y]:. Called with [5, 3], which case runs? Called with [3, 5], which case runs, and what are x and y afterward?
Show answer
With [5, 3] the first case runs, because the pattern matches and 5 > 3 is true. With [3, 5] the pattern of the first case matches and binds x = 3 and y = 5, but the guard 3 > 5 is false, so Python moves on. The second case matches and runs. Afterward x is 3 and y is 5.
Exercise
Write a function bucket(n) using match with guards that returns "small" for integers below 10, "medium" for integers from 10 to 99, and "large" for other integers. Return "not an int" for anything else.
Show answer
def bucket(n): match n: case int() if n < 10: return "small" case int() if n < 100: return "medium" case int(): return "large" case _: return "not an int"