Sub topic 1
Your first match statement
Overview
Python 3.10 added the match statement. At first glance it looks like the switch statement in C or Java. It does more than that. A switch compares one value against constants. A match statement compares a value against patterns, and a pattern can also pull the value apart and bind parts of it to names.
This chapter covers the basic shape of the statement, how Python runs it, and the mistakes people make in their first hour with it. Later chapters cover each pattern type in depth. Here we use only the simplest ones: literal values and the _ wildcard.
Prerequisites
This chapter assumes you already know the following:
- Python 3.10 or later is installed. Check with
python --version. On 3.9 or earlier,matchis a syntax error. - You can write functions with
if/elif/elseandreturnvalues. - You know the basic shape of lists, tuples, and dictionaries.
- You have seen classes and dataclasses, and
*unpacking in assignments such asfirst, *rest = items. These matter in later chapters more than this one.
The shape of a match statement
A match statement has a subject, which is the expression after the keyword match. It also has one or more case blocks, each with a pattern. Python tries the patterns in order and runs the body of the first one that matches.
def describe(code):
match code:
case 200:
return "OK"
case 404:
return "Not Found"
case _:
return "Unknown"
print(describe(200)) # OK
print(describe(404)) # Not Found
print(describe(500)) # UnknownThe pieces are:
match code:names the subject,code, and ends with a colon.- Each
caseline holds a pattern and ends with a colon. Its body is indented under it. case 200:is a literal pattern. It matches when the subject equals200.case _:is the wildcard pattern. It matches anything, so it works as a default branch.
The case lines are indented one level inside match, and each body is indented one more level. Getting the indentation wrong is a common first error.
How Python runs it
The working model has four rules.
- The subject is evaluated once. Python computes the subject, then tests each pattern against that single result.
- Cases are tried from top to bottom. The first pattern that matches wins.
- Only that case's body runs. There is no fall-through as in C, and no
breakis needed. - Execution continues after the whole
matchblock. This happens whether or not any case matched.
You can see rule 1 by using a subject with a side effect:
calls = 0
def get_command():
global calls
calls += 1
return "stop"
match get_command():
case "go":
print("going")
case "wait":
print("waiting")
case "stop":
print("stopping")
print(calls) # 1The function ran once, even though three patterns were tested. An if/elif chain written as if get_command() == "go": ... elif get_command() == "wait": ... would call it up to three times unless you stored the result first. The match statement stores the result for you.
A match with no matching case does nothing
If no case matches and there is no wildcard, Python does not raise an error. It skips the block silently.
def label(n):
match n:
case 1:
return "one"
case 2:
return "two"
print(label(1)) # one
print(label(3)) # Nonelabel(3) falls off the end of the function, so it returns None. That behavior can hide bugs. When every possible input should be handled, end the statement with case _: and either return a default or raise an exception:
def label(n):
match n:
case 1:
return "one"
case 2:
return "two"
case _:
raise ValueError(f"unsupported number: {n}")Matching more than one value
The subject can be any expression. A common trick is to put several values in a tuple so that one match tests them together:
def route(method, path):
match (method, path):
case ("GET", "/"):
return "home page"
case ("POST", "/login"):
return "log in"
case _:
return "not found"
print(route("GET", "/")) # home page
print(route("POST", "/login")) # log in
print(route("DELETE", "/")) # not foundEach case pattern here is a tuple of two literals. It matches only when the subject is a sequence of the same length and each element matches its own literal. The chapter on sequence patterns explains this in full. You may also write the subject without parentheses, as match method, path:. Python reads that as a tuple too.
match and case are soft keywords
match and case are soft keywords. They act as keywords only where a match statement can start. Everywhere else they are ordinary names, so existing code keeps working:
import re
match = re.match(r"\d+", "123 main street")
if match:
print(match.group()) # 123This is why Python 3.10 did not break the large amount of code that uses match as a variable name, such as the result of re.match. A line that starts with match, ends with a colon, and is followed by an indented case block is read as a statement. Otherwise it is an ordinary name.
It is a statement, not an expression
A match statement does not produce a value. You cannot write result = match x: .... To get a value out, either assign inside each case or put the match in a function and return from it:
def size_name(n):
match n:
case 1:
label = "small"
case 2:
label = "medium"
case _:
label = "large"
return label
print(size_name(2)) # medium
print(size_name(9)) # largeIf a case is missing and you read label afterwards, you get UnboundLocalError. The wildcard above prevents that.
Common errors in a first match statement
| Mistake | What happens | Fix | Column |
|---|---|---|---|
| Running on Python 3.9 or earlier | `SyntaxError` at the `match` line | Upgrade to 3.10 or later | |
| Missing colon after `match x` or after a `case` pattern | `SyntaxError: expected ':'` | Add the colon | |
| `case` lines not indented under `match` | `SyntaxError` or `IndentationError` | Indent each `case` one level | |
| Putting `case _:` before other cases | `SyntaxError: wildcard makes remaining patterns unreachable` | Move the wildcard to the end | |
| Expecting fall-through, so `case 1:` also runs `case 2:` | Only the first match runs | Combine values in one case (a later chapter shows `\ | `) |
| Using `match` where a value is needed | `SyntaxError` | Assign inside cases, or return from a function |
The wildcard error is worth noticing. Python refuses to compile a match statement that has a case after an always-matching one, because that case could never run. This is one of the few mistakes that Python catches before the code runs.
Match versus switch
Programmers coming from other languages often expect match to be a faster switch. It is not an optimization. Python tests the patterns one after another, so it is no faster than an if/elif chain. The gain is in clarity. A match statement states the shape of the data you expect and names its parts in one place. For a plain comparison of one value against a few constants, the two forms are equivalent. For nested or structured data, match is much shorter. The final chapter returns to when each form is the better choice.
Putting it together
This example combines everything above: a subject evaluated once, ordered cases, a literal pattern, a tuple subject, and a wildcard that raises on bad input.
def move_cost(terrain, wet):
match (terrain, wet):
case ("road", False):
return 1
case ("road", True):
return 2
case ("forest", _):
return 3
case _:
raise ValueError(f"unknown terrain: {terrain!r}")
print(move_cost("road", False)) # 1
print(move_cost("road", True)) # 2
print(move_cost("forest", True)) # 3The _ inside ("forest", _) means "any value in this position". Whether the forest is wet does not matter, so the pattern ignores it. A final _ handles everything else.
Exercise
A match statement has the cases case 1:, case 2:, and case 3: and no wildcard. The subject is 7. What happens, and why can that be a problem inside a function that is supposed to return a value?
Show answer
No case matches, so Python skips the whole block without raising an error and continues with the code after it. If the function has no other return, it returns None, which can hide the bug. Adding case _: that returns a default or raises an exception makes the unhandled input visible.
Exercise
What does this code print, and how many times does next(values) run?
values = iter(["b", "a"])
match next(values):
case "a":
print("first is a")
case "b":
print("first is b")
case "c":
print("first is c")
Show answer
It prints "first is b". The subject next(values) runs exactly once and returns "b". The cases are then tested against that one result, in order. The "a" case fails, the "b" case matches, its body runs, and Python skips the remaining cases.