Sub topic 4
Combining alternatives with |
This chapter assumes you know how match and case work, and that you can write literal patterns and the _ wildcard. It also assumes Python 3.10 or later.
Why you need alternatives
Often several inputs should lead to the same result. Without alternatives you would repeat the body:
def kind(code):
match code:
case 301:
return "Redirect"
case 302:
return "Redirect"
case _:
return "Other"
print(kind(302)) # RedirectAn or-pattern joins patterns with |. The case succeeds if any one of them matches.
def kind(code):
match code:
case 301 | 302 | 307 | 308:
return "Redirect"
case 404 | 410:
return "Gone"
case _:
return "Other"
print(kind(307)) # Redirect
print(kind(410)) # Gone
print(kind(200)) # OtherThe alternatives are tried from left to right. Matching stops at the first one that succeeds.
Alternatives inside larger patterns
The | operator works on any pattern, not only at the top level of a case. You can put it inside a sequence pattern to vary one position and keep the rest fixed.
def run(command):
match command.split():
case ["go" | "walk" | "run", direction]:
return f"move {direction}"
case ["quit" | "exit"]:
return "quit"
case _:
return "unknown command"
print(run("walk north")) # move north
print(run("exit")) # quit
print(run("jump")) # unknown commandIn the first case, the list must have exactly two elements. The first element can be any of three words, and the second is captured as direction.
Binding names in alternatives
Alternatives can capture values. Every alternative must bind the same set of names, because Python cannot know which one will match.
def radius(shape):
match shape:
case ["circle", r] | ["disc", r]:
return f"radius {r}"
case _:
return "no radius"
print(radius(["disc", 4])) # radius 4
print(radius(["square", 4])) # no radiusBoth alternatives bind r, so the body can use it safely. A pattern such as ["circle", r] | ["square", side] is a SyntaxError because the names differ.
Common mistakes
| Mistake | What happens | Fix | Column | Column |
|---|---|---|---|---|
| `case 301 or 302:` | `or` is not pattern syntax, so this is a SyntaxError | Use `case 301 \ | 302:` | |
| Different names in each alternative | SyntaxError | Bind the same names in all alternatives, or split into separate cases | ||
| `case _ \ | 200:` | SyntaxError, since `_` makes the rest unreachable | Put the catch-all last | |
| Using `\ | ` on a guard | Guards are ordinary expressions and `\ | ` is bitwise there | Use `or` in the guard: `case x if x < 0 or x > 9:` |
The last row matters because the two operators look similar. In a pattern, | means "or". In a guard after if, you write a normal Python condition, so you use or.
Exercise
Exercise
Write a function classify(token) using match. It should return "yes" for the strings "y", "yes" and "true", return "no" for "n", "no" and "false", and return "unknown" for anything else. What does classify("no") return, and why would case "y" or "yes": fail to do what you want?
Show answer
def classify(token):
match token:
case "y" | "yes" | "true":
return "yes"
case "n" | "no" | "false":
return "no"
case _:
return "unknown"
classify("no") returns "no". The form case "y" or "yes": is a SyntaxError because or is not allowed between patterns. Only | combines patterns.