Python 3.10 added the match statement, often called structural pattern matching. At its simplest it replaces a long chain of if/elif comparisons. Its real power is that a pattern can also unpack data: pull words out of a command, fields out of an object, or values out of a dictionary, all while checking its shape. This lesson covers literal, sequence, class and mapping patterns, guards and the wildcard.
In this lesson you will learn
- The basic
match/casesyntax and the_wildcard - Matching several values with
| - Capturing values and adding
ifguards - Sequence patterns for lists and tuples
- Class patterns and mapping (dictionary) patterns
You should know if/else, functions and dictionaries. You need Python 3.10 or later.
Values, Sequences and Guards
# match-case compares a value against patterns, top to bottom
def http_status(code):
match code:
case 200:
return "OK"
case 301 | 302: # either value
return "Redirect"
case 404:
return "Not Found"
case n if 500 <= n < 600: # capture + guard condition
return f"Server error {n}"
case _: # wildcard: anything else
return "Unknown"
for c in [200, 302, 404, 503, 418]:
print(c, "->", http_status(c))
# Sequence patterns unpack lists and tuples
def command(text):
match text.split():
case ["quit"]:
return "Goodbye"
case ["go", direction]:
return f"Moving {direction}"
case ["take", *items]:
return f"Taking {', '.join(items)}"
case []:
return "Say something"
case _:
return f"Unknown command: {text!r}"
for t in ["go north", "take pen notebook", "quit", "", "dance now"]:
print(command(t))
Output
200 -> OK
302 -> Redirect
404 -> Not Found
503 -> Server error 503
418 -> Unknown
Moving north
Taking pen, notebook
Goodbye
Say something
Unknown command: 'dance now'
match code:takes a subject, and eachcaseis tried from top to bottom. The first pattern that fits wins, and the rest are skipped. There is no fall-through, so nobreakis needed.case 301 | 302:matches either value.case n if 500 <= n < 600:captures the value into the namen, then the guard afterifmust also be true.case _:is the wildcard. It always matches, so it belongs last, likeelse.- Sequence patterns check the length and unpack in one step.
["go", direction]matches a two-word list starting with “go” and stores the second word.["take", *items]collects any number of remaining words. []matches an empty list, so an empty command gets its own message.
Class and Mapping Patterns
from dataclasses import dataclass
@dataclass
class Circle:
r: float
@dataclass
class Rect:
w: float
h: float
def area(shape):
match shape:
case Circle(r=r): # class pattern
return round(3.14159 * r * r, 2)
case Rect(w=w, h=h) if w == h: # a square
return f"square of {w * h}"
case Rect(w=w, h=h):
return w * h
case _:
raise TypeError(f"not a shape: {shape!r}")
print(area(Circle(2)), area(Rect(3, 3)), area(Rect(2, 5)))
# Mapping patterns match dictionaries, e.g. parsed JSON
events = [
{"type": "login", "user": "nusrat"},
{"type": "order", "user": "arif", "amount": 450},
{"type": "order", "user": "rina", "amount": 2600},
{"type": "logout"},
]
for e in events:
match e:
case {"type": "login", "user": str(name)}:
print(f"{name} logged in")
case {"type": "order", "amount": int(a)} if a > 1000:
print(f"large order: {a} taka from {e['user']}")
case {"type": "order", "user": name}:
print(f"order from {name}")
case {"type": other}:
print(f"ignored event: {other}")
Output
12.57 square of 9 10
nusrat logged in
order from arif
large order: 2600 taka from rina
ignored event: logout
case Circle(r=r):is a class pattern. It checks that the subject is aCircleand pulls out itsrattribute.- Order matters: the guarded square case comes before the general rectangle case, otherwise every rectangle, including squares, would match the general one first.
- Mapping patterns such as
{"type": "login", "user": str(name)}match dictionaries that contain at least those keys. Extra keys are allowed, which suits JSON data from an API. str(name)andint(a)check the type and capture the value at the same time.- Rina’s order of 2600 matched the “large order” case; Arif’s 450 failed its guard and fell through to the general order case.
Pattern Types
| Pattern | Example | Matches |
|---|---|---|
| Literal | case 404: | An equal value |
| Or | case "y" | "yes": | Any of the alternatives |
| Capture | case x: | Anything, and binds it to x |
| Wildcard | case _: | Anything, without binding |
| Sequence | case [first, *rest]: | Lists and tuples of a matching length |
| Mapping | case {"id": i}: | Dictionaries containing those keys |
| Class | case Point(x=0): | Instances with matching attributes |
| Guard | case n if n > 0: | Any pattern plus an extra condition |
Common Mistakes
- Matching against a variable:
case limit:does not compare with a variable calledlimit; it captures anything into a new name. Use a dotted name such ascase Status.OK:, or a guard. - Putting the wildcard or a broad pattern first, so later cases can never run.
- Using
matchfor a simple two-way choice, whereif/elseis clearer. - Expecting strings to match as sequences. A string does not match
[a, b]; split it first, as the command example does.
Practice Exercises
Exercise 1. Write grade(mark) using match with guards: 80 and above “A+”, 70–79 “A”, 60–69 “B”, anything else “F”.
Show answer
def grade(mark):
match mark:
case m if m >= 80:
return "A+"
case m if m >= 70:
return "A"
case m if m >= 60:
return "B"
case _:
return "F"
print(grade(85), grade(72), grade(40)) # A+ A F
Exercise 2. Match a point given as a tuple (x, y) and print “origin”, “on the x-axis”, “on the y-axis” or “elsewhere”.
Show answer
def where(point):
match point:
case (0, 0):
return "origin"
case (x, 0):
return "on the x-axis"
case (0, y):
return "on the y-axis"
case _:
return "elsewhere"
print(where((0, 0)), where((5, 0)), where((0, -2)), where((3, 4)))
Frequently Asked Questions
Is match-case the same as switch in other languages?
It covers what a switch does, but it is more powerful: it can unpack sequences, dictionaries and objects, bind variables and check types. It also never falls through from one case to the next.
Is match faster than if/elif?
Not noticeably for most code. Choose match when it makes the code clearer, especially when you are checking the shape of data rather than a single value.
Summary
matchtries eachcasein order and runs the first that fits.- Patterns can compare, capture, unpack and check types.
- Guards add extra conditions;
_catches everything else. - A bare name in a pattern captures; it never compares with an existing variable.
Next: Python Built-in Functions.
