`match` / `case`
match / case is structural pattern matching: you compare a value against shapes, bind the pieces that match, and run the first successful case. It is not a C-style switch on integers.
Detailed Explanation
A long if / elif chain that picks a value apart is hard to read. You test isinstance, then index, then check a key, then bind locals by hand. match, added in Python 3.10, does that unpacking in the case label itself.
match subject: evaluates the subject once. Each case pattern: is tried in order. The first pattern that matches runs its block, and matching stops. A trailing case _: is the wildcard, the equivalent of else.
Patterns come in layers. A literal pattern matches equality: case 404:. An or-pattern matches any of several: case 401 | 403:. A capture pattern binds a name: case status:. A sequence pattern unpacks: case [method, path]:. A mapping pattern pulls keys: case {"error": msg}:. A class pattern matches a type and selected attributes: case Point(x=0, y=y):.
Guards add a boolean test after a match: case [x, y] if x == y:. The pattern binds first, then the guard runs. If the guard is false, matching continues at the next case. That is how you keep a shape check and a value check in one clause.
Matching is not quite equality. A class pattern uses __match_args__ or keyword attributes, and it accepts subclasses. A mapping pattern ignores extra keys by default; a sequence pattern does not ignore extra items unless you write a starred rest. case [first, *rest]: is the list analogue of extra keys.
Capture names are ordinary bindings. They leak into the surrounding scope, like names assigned in an if. After case [x, y]:, x and y exist below the match if that case ran. If you need a name only inside the case, keep the block self-contained.
Use match when the interesting part is the shape of the data: a parsed JSON object, a command tuple, an AST node, an HTTP result. Use if when the interesting part is a computed predicate. Do not rewrite every if as match. The feature pays for itself when it removes a nest of isinstance and indexing.
Code Examples
def describe(status: int, body: dict) -> str:
match status, body:
case 200, {"user": name}:
return f"ok:{name}"
case 401 | 403, _:
return "denied"
case 404, _:
return "missing"
case code, {"error": msg} if code >= 500:
return f"server:{msg}"
case _:
return "unknown"
print(describe(200, {"user": "ada"})) # ok:ada
print(describe(403, {})) # denied
print(describe(503, {"error": "timeout"})) # server:timeoutclass Point:
__match_args__ = ("x", "y")
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def axis(point: Point) -> str:
match point:
case Point(0, 0):
return "origin"
case Point(0, y):
return f"y-axis:{y}"
case Point(x, 0):
return f"x-axis:{x}"
case Point(x, y):
return f"point:{x},{y}"
print(axis(Point(0, 4))) # y-axis:4Common Gotchas
A bare name in a case captures, it does not compare
`case status:` matches everything and binds `status`. To match an existing variable, write `case Status.NOT_FOUND:` or `case code if code == expected:`.
Mapping patterns ignore extra keys
`case {"id": n}:` matches `{"id": 1, "extra": True}`. Sequence patterns do not ignore extra items unless you use `*rest`.
`match` needs Python 3.10+
on 3.9 the keyword is a `SyntaxError`. Check the version before you ship it.