match Statement
Structural pattern matching — compare a value's shape against a series of patterns and run the first one that fits.
match subject:
case pattern:
...
Purpose
match compares a subject value against a sequence of case patterns, top to bottom, and runs
the body of the first one that matches. A bare case _: matches anything and conventionally goes
last, as a catch-all.
Example
def describe_status(code: int) -> str:
match code:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _:
return "Unknown"
Behavior notes
- Patterns can do more than match literal values:
case [x, y]destructures a two-element sequence,case {"status": code}matches a mapping with that key, andcase int() | float():matches by type. This entry covers only literal-value matching, which is the form most beginner code needs — the richer pattern forms are worth exploring once this one feels comfortable, via the officialmatchstatement documentation. case _:is a wildcard, not a variable capture in the usual sense — it matches anything and binds nothing.- Unlike a chain of
if/elif,matchcan destructure its subject as part of matching, not just compare it — that’s the actual featureif/elifcan’t replicate.
Common mistakes
- Reaching for
matchas a drop-in replacement for a simpleif/elifchain comparing one variable to a handful of literals — either works for that case, andif/elifis often more familiar to a reader seeing it for the first time.matchearns its place once the patterns genuinely destructure structure, not just compare literals. - Forgetting the wildcard case (
case _:) and assuming an unmatched value silently does nothing — it does, actually: amatchstatement with no matching case and no wildcard simply falls through with no error, which can hide a genuine bug.
Implementation notes
match is a language feature — but a real, version-gated one: unavailable before Python 3.10. Any
codebase or example that needs to support earlier versions has to use an if/elif chain instead.