Python Match
The match statement compares a value against a series of patterns and runs the block of the first one that fits. It looks like the switch statement from other languages, but it is more powerful: it can also look inside lists, tuples, dictionaries and objects.
Note:
matchrequires Python 3.10 or newer. On older versions useif/elifchains.
Matching literal values
def http_status(code):
match code:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _:
return "Unknown"
for c in [200, 404, 418]:
print(c, http_status(c))200 OK
404 Not Found
418 Unknown
case _: is the wildcard — it matches anything, so it acts like a default. Only the first matching case runs; there is no "fall-through" and no break needed.
Several values in one case
Use | ("or") to accept alternatives:
def day_type(day):
match day.lower():
case "sat" | "sun":
return "weekend"
case "mon" | "tue" | "wed" | "thu" | "fri":
return "weekday"
case _:
return "not a day"
print(day_type("Sun"), day_type("wed"), day_type("xyz"))weekend weekday not a day
Capturing values and guards
A bare name in a pattern captures the value. An if after the pattern is a guard that adds an extra condition:
def classify(n):
match n:
case 0:
return "zero"
case x if x < 0:
return f"negative ({x})"
case x if x % 2 == 0:
return f"even ({x})"
case x:
return f"odd ({x})"
for n in [0, -3, 8, 5]:
print(classify(n))zero
negative (-3)
even (8)
odd (5)
Matching sequences
Patterns can describe the shape of a list or tuple. This makes match great for parsing simple commands:
def run(command):
match command.split():
case ["quit"]:
return "Goodbye!"
case ["go", direction]:
return f"You walk {direction}."
case ["take", item, "from", place]:
return f"You take the {item} from the {place}."
case ["say", *words]:
return "You say: " + " ".join(words)
case _:
return "I don't understand."
for cmd in ["go north", "take key from table", "say hello there", "quit", "dance"]:
print(run(cmd))You walk north.
You take the key from the table.
You say: hello there
Goodbye!
I don't understand.
*words captures any remaining items into a list, just like in unpacking.
Matching dictionaries
A mapping pattern checks that certain keys exist and captures their values. Extra keys are ignored:
events = [
{"type": "click", "x": 10, "y": 20},
{"type": "key", "key": "Enter"},
{"type": "scroll"},
]
for event in events:
match event:
case {"type": "click", "x": x, "y": y}:
print(f"Click at ({x}, {y})")
case {"type": "key", "key": k}:
print(f"Key pressed: {k}")
case {"type": other}:
print(f"Unhandled event: {other}")Click at (10, 20)
Key pressed: Enter
Unhandled event: scroll
Matching objects
Class patterns check the type and can pull out attributes. They work especially well with dataclasses:
case Point(x=0, y=0):
print("origin")
case Point(x=0, y=y):
print(f"on the y-axis at {y}")Pattern summary
| Pattern | Matches |
|---|---|
42, "text", None |
that exact value |
_ |
anything (wildcard) |
name |
anything, and binds it to name |
a | b |
either alternative |
[x, y] |
a sequence of exactly two items |
[first, *rest] |
a sequence of one or more items |
{"key": v} |
a mapping with that key |
Point(x=0) |
a Point instance whose x is 0 |
pattern if cond |
the pattern, only when cond is true |
Tip: A bare name always captures. To compare against a constant stored in a variable, use a dotted name such as
Color.RED, otherwisecase RED:would capture everything!
Test yourself
Which minimum Python version supports match?
- 3.6
- 3.8
- 3.10
- 3.12
What does case _: do?
- Matches only None
- Matches anything, acting as a default
- Matches an empty string
- Causes a syntax error
Which pattern matches the list ["go", "east"] and captures "east"?
- case "go east":
- case ["go", direction]:
- case go(direction):
- case {"go": direction}: