Sub topic 4
Combining alternatives with |
An or-pattern lets one case block handle several different patterns by joining them with |. This chapter covers where | can appear, how alternatives are tried, and the rules about bound names that produce syntax errors.
This chapter assumes you have Python 3.10 or later. It also assumes you know the basic match and case syntax, literal patterns, and the _ wildcard and capture names from the earlier chapters. You should also be comfortable with lists and tuples.
The basic form
An or-pattern is two or more patterns separated by |. The case matches if any one of them matches. This is the same idea as writing code in (301, 302), but it works for any pattern, not only literals.
def classify(code):
match code:
case 200 | 201 | 204:
return "success"
case 301 | 302 | 307 | 308:
return "redirect"
case 400 | 401 | 403 | 404:
return "client error"
case _:
return "other"
print(classify(204)) # success
print(classify(308)) # redirect
print(classify(500)) # otherWrite |, not the keyword or. The text case 200 or 201 is a syntax error, because case expects a pattern and not a boolean expression.
How alternatives are tried
Python tries the alternatives from left to right and stops at the first one that matches. The case body then runs once. It does not run once per matching alternative.
For literal alternatives the order makes no difference to the result. It matters when the alternatives are broader patterns, because the first alternative to match decides which names get bound.
Alternatives inside larger patterns
An or-pattern does not have to be the whole pattern. You can put it inside a sequence, mapping, or class pattern, which keeps the surrounding structure from being repeated. Use parentheses to mark the part that is the alternative.
def move(command):
match command.split():
case ["go" | "walk" | "run", ("north" | "south" | "east" | "west") as direction]:
return f"moving {direction}"
case ["quit" | "exit"]:
return "leaving"
case _:
return "unknown command"
print(move("run east")) # moving east
print(move("exit")) # leaving
print(move("go upward")) # unknown commandWithout or-patterns, the first case would need twelve separate case lines or an extra check inside the body. The as direction part binds the value that matched the alternatives. It is covered fully in a later chapter. The parentheses around the alternatives are required for readability here, since as has lower precedence than |.
Every alternative must bind the same names
Alternatives may capture values, but each alternative must bind exactly the same set of names. Python checks this when it compiles the code, not when it runs it. Here is a valid case.
def on_axis(point):
match point:
case (0, y) | (y, 0):
return f"on an axis, other coordinate {y}"
case _:
return "off the axes"
print(on_axis((0, 5))) # on an axis, other coordinate 5
print(on_axis((4, 0))) # on an axis, other coordinate 4
print(on_axis((1, 1))) # off the axesBoth alternatives bind y, so the body can always use it. If one alternative bound y and the other did not, the body would have no reliable value for y. Python rejects that case before the program runs. You can see the error by compiling a snippet.
source = """
match point:
case (0, y) | (x, 0):
pass
"""
try:
compile(source, "<demo>", "exec")
except SyntaxError as error:
print(error.msg) # alternative patterns bind different namesThe exact wording of the message can differ between Python versions. If you see this error, look for a name that appears in only some alternatives. The fix is either to make the names match or to split the alternatives into separate cases.
Irrefutable alternatives must come last
A pattern that always matches is called irrefutable. The wildcard _ and a bare capture name such as x are irrefutable. If one appears in an or-pattern before the final alternative, everything after it could never be reached, so Python rejects it at compile time.
for pattern in ("_ | 1", "x | 1", "1 | _"):
source = f"match value:\n case {pattern}:\n pass\n"
try:
compile(source, "<demo>", "exec")
print(pattern, "-> compiles")
except SyntaxError as error:
print(pattern, "->", error.msg)The first two patterns fail to compile, with messages saying the wildcard or the captured name makes the remaining patterns unreachable. The third compiles. Even so, 1 | _ is the same as _, so the 1 adds nothing. If you write an or-pattern that ends in _, ask whether you really want just a wildcard case.
The same rule applies to whole cases. An irrefutable case must be the last case in the match statement, or Python raises a syntax error about unreachable patterns. Other chapters on evaluation order and pitfalls build on this.
Singletons and numeric equality
Literal patterns for None, True, and False are compared by identity (is). Other literals are compared with ==. This matters in an or-pattern that mixes them.
def describe(value):
match value:
case None | False:
return "nothing or false"
case 0 | 0.0:
return "zero"
case "" | []:
return "empty text or empty list"
case _:
return "something else"
print(describe(None)) # nothing or false
print(describe(0.0)) # zero
print(describe("")) # empty text or empty list
print(describe(False)) # nothing or falseTwo details are worth knowing. First, 0 | 0.0 is redundant, because 0 == 0.0 is true, so either literal alone would match both values. Second, the pattern [] is a sequence pattern that matches only an empty list or tuple. It does not match every falsy value. Because False is tested before 0, the value False takes the first case. Without that ordering, False == 0 would let it match the zero case.
Or-patterns and guards
A guard follows the whole case pattern, so it applies to the entire or-pattern. Python finds the first alternative that matches, binds its names, and only then evaluates the guard. If the guard is false, the case fails and Python moves to the next case. It does not go back and try the remaining alternatives of the same or-pattern.
def schedule(day, on_call):
match day:
case "sat" | "sun" if on_call:
return "weekend, on call"
case "sat" | "sun":
return "weekend"
case _:
return "weekday"
print(schedule("sat", True)) # weekend, on call
print(schedule("sun", False)) # weekend
print(schedule("mon", True)) # weekdayThe second case repeats the or-pattern without a guard to handle everyone who is not on call. That repetition is a normal and readable way to write it.
Common mistakes
| Mistake | What happens | Fix | Column | Column |
|---|---|---|---|---|
| Writing `case 1 or 2:` | Syntax error | Use `case 1 \ | 2:` | |
| Binding different names in each alternative | Syntax error at compile time | Bind the same names in every alternative, or split into cases | ||
| Putting `_` or a bare name before the last alternative | Syntax error, unreachable alternatives | Move it last, or drop the alternatives it makes pointless | ||
| Expecting a failed guard to try the next alternative | The whole case is skipped | Write separate cases, as in `schedule` above | ||
| Using a bare name like `RED \ | GREEN` to compare constants | Syntax error, because a bare name captures and cannot be followed by alternatives | Use dotted names such as `Color.RED \ | Color.GREEN` |
The last row connects to a later chapter on value patterns. A bare name in a pattern is a capture, so it is irrefutable, and the previous section's rule makes it an error when followed by more alternatives.
Choosing between one case and several
Combine alternatives when the body is identical and the patterns share the same bound names. Use separate cases when the bodies differ, or when the alternatives bind different names. A long or-pattern of many unrelated shapes is usually a sign that the case is doing too much work.
Exercise
Why does case [x] | [x, _]: compile while case [x] | [y, _]: does not, and what does the first one match?
Show answer
Python requires every alternative in an or-pattern to bind the same set of names. In the first pattern both alternatives bind only x, so it compiles. In the second, the alternatives bind x and y respectively, which raises a SyntaxError ("alternative patterns bind different names"). The first pattern matches a sequence of length 1 or length 2, and binds x to the first element in both cases.
Exercise
What does this function return for check(0), check(False), and check("n")?
def check(v):
match v:
case False | "n" | "no":
return "negative"
case 0:
return "zero"
case _:
return "other"
Show answer
check(0) returns "zero" and check(False) returns "negative". check("n") returns "negative". False is compared by identity, and 0 is False is not true, so 0 skips the first case. False matches the first alternative directly, so it never reaches case 0, even though False == 0 is true.