Python Structural Pattern Matching
Structural pattern matching looks inside a value. A pattern can pull out the parts a program needs.
Match a sequence
The pattern pulls the list apart. Each part gets its own name.
command = ["move", 3, 4]
match command:
case [action, x, y]:
print(action, x + y)
case _:
print("Unknown")Match a mapping
The pattern names the keys it wants. Extra keys in the dict are fine.
event = {"type": "click", "x": 10, "y": 20}
match event:
case {"type": "click", "x": x, "y": y}:
print("Click at", x, y)
case _:
print("Other event")Match a class
__match_args__ says x comes first and y second. The pattern Point(0, y) uses that order.
class Point:
__match_args__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
place = Point(0, 5)
match place:
case Point(0, 0):
print("Origin")
case Point(0, y):
print("On the y-axis at", y)
case _:
print("Elsewhere")Try two patterns with or
The bar means or. Either code counts as success here.
code = 201
match code:
case 200 | 201:
print("Success")
case _:
print("Other")Add a guard and keep the value
The guard is the if part after the pattern. The word as keeps the whole number in shown.
value = -7
match value:
case int(n) as shown if n < 0:
print("Negative:", shown)
case int(n):
print("Number:", n)
case _:
print("Not a number")Example
def run(command):
match command:
case ("move", direction, int(steps)):
print("Move", direction, "by", steps)
case ("say", *words):
print("Say:", " ".join(words))
case ("quit",):
print("Goodbye")
case _:
print("Unknown command")
run(("move", "north", 3))
run(("say", "hello", "there"))
run(("dance", 2))
run(("quit",))Key points
- Sequence pattern: a pattern shaped like a list or tuple.
- It binds each part to a name.
- Mapping pattern: a pattern shaped like a dict.
- It binds values by their keys.
- Class pattern: a pattern shaped like a class call.
- It binds values from an object.
- __match_args__: the order a class pattern uses for positional values.
- Guard: an extra if test after a pattern.
- The case wins only if the test passes too.
- Use as to bind the whole matched part to one name.
- Pattern matching examines a value from the inside and binds the parts it finds.
In this example, each command is a tuple of words and numbers. The first case needs the word move, a direction, and an int for steps. The second case takes the word say and collects the rest as words. The star pattern gathers those extra items into a list. The third case is the exact tuple with only quit. Any other shape falls to the last case, which prints Unknown command.
Note
A plain name in a pattern always matches.
It binds the value instead of testing it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which pattern fits a value like {"type": "click", "x": 4}?