Sub topic 1
Your first match statement
Prerequisites
This chapter assumes you have:
- Python 3.10 or later installed. Check with
python --version. - Basic Python syntax: functions, conditionals, and return values.
- Familiarity with lists, tuples, and dictionaries.
Later chapters also use classes, dataclasses, and * unpacking. You don't need them yet.
What match does
The match statement, added in Python 3.10, compares one value against a series of patterns. It runs the block of the first pattern that fits. It is often called structural pattern matching, because patterns can describe the shape of data as well as simple values. In this chapter you will use only the simplest patterns.
A match statement has two parts:
- The subject is the expression after
match. Python evaluates it once. - Each
caseline holds a pattern followed by an indented block. The block runs only if the pattern fits the subject.
A first example
def http_status(code):
match code:
case 200:
return "OK"
case 301 | 302:
return "Redirect"
case 404:
return "Not Found"
case _:
return "Unknown"
print(http_status(302)) # Redirect
print(http_status(500)) # UnknownRead it from the top. The subject is code. For http_status(302), Python tries case 200 and finds no match. It then tries case 301 | 302, where | means "or", and finds a match. It runs return "Redirect" and stops looking.
The last case, case _, uses _, the wildcard pattern. It matches any value, so it works as a default branch. Later chapters cover wildcards and | in detail.
How the flow works
Three rules follow from this flow:
- Cases are tried from top to bottom.
- Only the first matching case runs. There is no fall-through as in C-style
switchstatements, so you never writebreak. - If no case matches and there is no wildcard, nothing happens and no error is raised.
The third rule can hide mistakes. This version has no default case:
def label(code):
match code:
case 200:
return "OK"
print(label(404)) # NoneThe match finds nothing, the function reaches its end, and Python returns None. If a missing case is a bug in your program, end with a case _ that raises an error.
def label(code):
match code:
case 200:
return "OK"
case _:
raise ValueError(f"unexpected status: {code}")match and case are soft keywords
match and case are soft keywords. They act as keywords only where a match statement is expected. Code that uses match as an ordinary name, such as match = re.match(...), keeps working in 3.10 and later.
Common first mistakes
- Forgetting the colon after the subject or after a pattern.
- Using
==inside a pattern. Writecase 200:, notcase == 200:. - Expecting several cases to run. Only the first match runs.
- Running the code on Python 3.9 or earlier, which reports a
SyntaxError.
Exercise
What does this code print, and why? def size(n): match n: case 1 | 2: return "small" case 2 | 3: return "medium" case _: return "large" print(size(2)) print(size(3)) print(size(9))
Show answer
It prints small, medium, and large. For 2, the first case matches, so the second case is never tried, even though it also contains 2. For 3, the first case fails and the second matches. For 9, only the wildcard matches.