Structural Pattern Matching in Python: Beyond a switch Statement
This article explains how the match statement of Python recognizes the shape of data through literal, value, sequence, mapping and class patterns, and which rules make it differ from the switch statement of other languages.
A long chain of if, elif and else that inspects the type, the length and the contents of a value mixes two tasks: recognizing the shape of the data and extracting its parts. Python 3.10 introduced the statement match (PEP 634), known as structural pattern matching, which performs both tasks in a single declarative construct. The present article examines the five main kinds of patterns, namely literal, value, sequence, mapping and class patterns, together with guards and alternatives, and it identifies the rules that make the statement behave differently from the switch of other languages. A pattern that describes the expected shape of a value, and names its parts at the same time, is the secret weapon of this statement.
Literal and Value Patterns
The simplest patterns compare the subject with a constant. A literal such as 200 or "ok" is compared with ==, a dotted name such as HTTPStatus.OK is looked up and compared in the same way, the operator | combines alternatives, as binds the matched value to a name, and the wildcard _ matches anything.
from http import HTTPStatus
def describe(status):
match status:
case HTTPStatus.OK:
return "success"
case HTTPStatus.NOT_FOUND | HTTPStatus.GONE:
return "missing resource"
case 500 | 502 | 503 as code:
return f"server error {code}"
case _:
return "unhandled status"
print(describe(200)) # Output: success
print(describe(410)) # Output: missing resource
print(describe(503)) # Output: server error 503
print(describe(418)) # Output: unhandled status
The integer 200 matches HTTPStatus.OK because the enumeration member is equal to it. The cases are tried from top to bottom and the first one that matches wins, so the statement is not a jump table and has no fall-through between cases. Up to this point, match is only a more compact if chain; its real value appears when the subject has an internal structure.
Sequence Patterns
A sequence pattern, written with square brackets or parentheses, matches a list or tuple of a given length and binds its elements to names. A starred name collects the remaining elements, so a single pattern can accept sequences of variable length. The following example interprets the commands of a small key-value store.
store = {}
def execute(command):
match command.split():
case ["get", key]:
return store.get(key, "(missing)")
case ["set", key, value]:
store[key] = value
return "stored"
case ["delete", *keys] if keys:
for key in keys:
store.pop(key, None)
return f"deleted {len(keys)}"
case []:
return "empty command"
case _:
return f"invalid: {command!r}"
print(execute("set colour blue")) # Output: stored
print(execute("get colour")) # Output: blue
print(execute("delete colour size")) # Output: deleted 2
print(execute("get colour")) # Output: (missing)
print(execute("set colour")) # Output: invalid: 'set colour'
Crafting systems in many games offer a useful image for this behaviour: the game recognizes a recipe by the arrangement of the items placed on a grid, and a slot marked for "any plank" accepts whatever plank is placed there. In the same way, ["set", key, value] requires a list of exactly three elements whose first element is "set", and it binds the other two to names, without any explicit check of len(command) or indexing. The analogy, however, stops at this point, because a game usually forbids two recipes with the same arrangement, whereas match accepts overlapping cases and simply executes the first one that fits. The if keys that follows the third pattern is a guard: the case matches only when the pattern fits and the condition is true, so "delete" without arguments falls through to the invalid command. Strings, bytes and byte arrays never match sequence patterns, which prevents a string from being split into characters by accident.
Mapping Patterns
A mapping pattern, written with braces, matches any mapping that contains the listed keys, and it ignores the remaining keys. Nested patterns can check the type of each value, and **rest collects the keys that the pattern does not mention, which suits data decoded from JSON.
def handle(event):
match event:
case {"type": "login", "user": str(user)}:
return f"login by {user}"
case {"type": "purchase", "amount": int(amount) | float(amount)} if amount > 0:
return f"purchase of {amount}"
case {"type": kind, **details}:
return f"unhandled {kind} with keys {sorted(details)}"
case _:
return "malformed event"
print(handle({"type": "login", "user": "ada", "ip": "10.0.0.1"})) # Output: login by ada
print(handle({"type": "purchase", "amount": 19.9})) # Output: purchase of 19.9
print(handle({"type": "purchase", "amount": -5})) # Output: unhandled purchase with keys ['amount']
print(handle({"user": "ada"})) # Output: malformed event
The subpattern str(user) checks that the value is a string and binds it, and the alternative int(amount) | float(amount) accepts either numeric type; both alternatives must bind the same names. The purchase with a negative amount fails the guard and is handled by the generic case, which receives the type and the remaining keys.
Class Patterns
A class pattern, written like a constructor call, checks the type of the subject with isinstance and matches its attributes. Keyword subpatterns name the attributes directly, while positional subpatterns are mapped to attribute names through the class attribute __match_args__, which @dataclass generates automatically from the fields.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def locate(point):
match point:
case Point(0, 0):
return "origin"
case Point(x, 0) | Point(0, x):
return f"on an axis at {x}"
case Point(x=x, y=y) if x == y:
return f"on the diagonal at {x}"
case Point():
return "elsewhere"
print(Point.__match_args__) # Output: ('x', 'y')
print(locate(Point(0, 0))) # Output: origin
print(locate(Point(0, 5))) # Output: on an axis at 5
print(locate(Point(2, 2))) # Output: on the diagonal at 2
print(locate(Point(1, 4))) # Output: elsewhere
The pattern Point(x, 0) is therefore equivalent to Point(x=x, y=0). A class without __match_args__ accepts only keyword subpatterns, and built-in types such as int or str accept a single positional subpattern that matches the whole subject, as in the str(user) of the previous example.
Pitfalls of Pattern Matching
The syntax of patterns resembles ordinary expressions, but several of its elements mean something different. Five pitfalls are distinguished, which are the following:
- Bare names capture.
case NOT_FOUND:does not compare with a constant; it binds any value to the nameNOT_FOUND. Constants must be written as dotted names, such asHTTPStatus.NOT_FOUNDorCodes.NOT_FOUND. - Order decides. The first matching case wins, so a general case placed before a specific one hides it.
- Equality, not identity. Literals other than
True,FalseandNoneare compared with==, socase 1:also matchesTrueand1.0. - Strings are not sequences. A sequence pattern never matches a string; a pattern such as
str()is required. - Extra keys pass. A mapping pattern ignores unlisted keys, so it does not validate that a dictionary contains nothing else.
The first and third pitfalls are reproduced in the following example.
source = """
NOT_FOUND = 404
match 200:
case NOT_FOUND:
pass
case _:
pass
"""
try:
compile(source, "<example>", "exec")
except SyntaxError as error:
print(error.msg) # Output (CPython 3.12): name capture 'NOT_FOUND' makes remaining patterns unreachable
def kind(value):
match value:
case 1:
return "the integer one"
case True:
return "the boolean true"
case str() | bytes():
return "text"
case [*items]:
return f"sequence of {len(items)}"
print(kind(True)) # Output: the integer one
print(kind(1.0)) # Output: the integer one
print(kind("abc")) # Output: text
print(kind((1, 2))) # Output: sequence of 2
The compiler rejects the bare name because it would match everything and make the next case unreachable; if the capture is the last case, however, no error is raised, and the name is silently rebound to the subject. The function kind never reaches case True, because True == 1 and the earlier case already matched.
Choosing the Right Construct
Consequently, match pays off when the decision depends on the shape of the data, and an ordinary construct remains clearer in the other cases, as the following table summarizes.
| Situation | Recommended construct |
|---|---|
| One or two simple conditions | if / elif |
| Many constant values mapped to results | A dictionary lookup |
| Commands, messages or decoded JSON with several shapes | match with sequence or mapping patterns |
| Trees and records of known classes | match with class patterns |
| Behaviour selected by the type of an argument, open to extension | functools.singledispatch |
| Interchangeable algorithms chosen at runtime | A dictionary of callables or strategy objects |
The last two rows are alternatives that keep the decision extensible from outside the function, as described in the article devoted to singledispatch and in the article devoted to the Strategy pattern; a match statement, by contrast, keeps every case in one place, which is an advantage when the set of shapes is closed.
Conclusion
It is concluded that structural pattern matching replaces chains of type checks, length checks and indexing with patterns that describe the shape of a value and bind its parts in one step. Its correct use depends on a few rules: cases are tried in order, bare names capture instead of comparing, literals are compared by equality, and strings never match sequence patterns. This magic is most effective with data whose shapes are known in advance, such as commands, decoded JSON and records. Dataclasses, whose automatically generated __match_args__ made the class patterns of this article so concise, are developed in a future article of this series.