Dispatch by shape: Python match statements
match is not switch: only the first matching branch runs, and it can take a value apart into variables. Following Tutorial section 4.7: literals and combined patterns, bindings, class and nested patterns, guards, sequence and mapping patterns — plus a 100-mistake breakdown from a fictional bookstore script.

First, the boundaries of this guide. This is the eighth article in the "Python basics" series, continuing from the first seven: the first covered variables, types, and control flow; the second, functions and modules; the third, classes and inheritance; the fourth, exception handling; the fifth, file I/O; the sixth, comprehensions and generators; the seventh, decorators. This one covers the match statement: dispatching by the shape of a value, one match standing in for a whole chain of if and elif. The "Morning Light Bookstore" used below is the same fictional practice project as before: a small street bookstore whose bookkeeping script can already count stock, apply discounts, manage books with classes, catch errors, save its ledger to files, pick books with comprehensions, and add timing to functions with decorators. The new problem here is that the shop's paperwork comes in several shapes — sales, restocking, returns — and asking "is it this kind, is it that kind" with if and elif gets long and easy to get wrong, while match dispatches by shape, so you can see at a glance which road each kind of paperwork takes. Everything said here about the match statement comes from the official Python Tutorial, Chapter 4, "More Control Flow Tools", section 4.7, "match Statements"; more examples and a fuller explanation are in PEP 636, which the Tutorial itself points to. See each article's meta information and evidence record for the sources. All operations, code, and numbers using the Morning Light Bookstore are invented to explain the technique and are not real records. By the end of this guide, you should be able to do five things: write literal patterns, combined patterns, and the wildcard; use patterns to bind variables and take apart tuples and dictionaries; write class patterns and nested patterns; add guards to cases and explain that binding happens before the guard is evaluated; and explain how match and if/elif divide the work, knowing when to use which. The boundary with the first guide is this: that guide covered if, elif, and else; this one does not repeat conditional logic, and only covers this one new way of writing it — dispatching by shape. The boundary with the third guide is this: that guide covered how to write classes and read attributes; this guide's class patterns only use classes to take data apart, and do not cover inheritance or methods.
Step 1: match is not switch — only the first matching branch runs
The official Tutorial, section 4.7, opens with the point plainly: a match statement takes an expression and compares its value to successive patterns given as one or more case blocks. Superficially it resembles a switch statement in C, Java, or JavaScript, but it is more similar to pattern matching in languages like Rust or Haskell. Only the first pattern that matches gets executed, and it can also extract components — sequence elements or object attributes — from the value into variables. If no case matches, none of the branches is executed. The simplest form compares a subject value against one or more literals, in the official example of returning a sentence for an HTTP status code:
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
http_error(400) returns "Bad request", http_error(404) returns "Not found", http_error(418) returns "I'm a teapot", and http_error(500) returns "Something's wrong with the internet". Note the last line: the variable name _ acts as a wildcard and never fails to match, written last as a catch-all. Also note the biggest difference from switch: match stops at the first branch that matches and never falls through into the next one the way a C switch does, and there is no need to write break. One more detail worth remembering: the value being compared is evaluated only once — if it is a function call, the whole match calls it once, not once per case:
evals = {"n": 0}
def subject():
evals["n"] += 1
return 404
match subject():
case 404:
out = "not found"
case _:
out = "other"
evals["n"] # 1, called only once
out # 'not found'
My judgement is this: the way to read match is "whatever shape this value has, that is the road it takes" — think about the shape first, and the branch second; the way to read if and elif is "is this condition true", and the two should not be mixed up. When no case matches and there is no case _ either, the match statement does nothing at all and execution simply moves on; if it sits inside a function, the function runs to its end and returns None:
def classify(n):
match n:
case 0:
return "zero"
classify(5) # None; no case matched, no case _, quietly returns None
That is why case _ in step 1 must not be skipped — not every unmatched value raises an error; most of the time it just silently does nothing.
Step 2: Literals can be combined — one case for several values
When several literals should take the same branch, you do not need to write the case three times: join them with | (read as "or"). The official example:
case 401 | 403 | 404:
return "Not allowed"
The bookstore version: three kinds of client error all mean "not allowed in":
def client_error(status):
match status:
case 401 | 403 | 404:
return "Not allowed"
case _:
return "Something else"
client_error(401) # 'Not allowed'
client_error(403) # 'Not allowed'
client_error(404) # 'Not allowed'
client_error(500) # 'Something else'
401, 403, and 404 all return 'Not allowed', and 500 returns 'Something else'. A combined pattern can only join literals and other things that can be compared directly — it cannot join variable bindings; binding variables and taking structures apart is the next step's job. It is also worth settling now when to use match and when to stay with if and elif: if the question is "which of a few fixed values is this equal to", match reads more clearly; if the question is about a range, a size, or a truth value — "stock below 10", "price above 50" — if and elif fit better, since a match guard can express those too but gets just as wordy once there are many of them. The paperwork dispatch in step 10 is what match is for: five kinds of paperwork, five shapes, one sentence per shape; written with if and elif, that would be five repetitions of order["kind"] == ... with a catch-all easy to forget. My judgement is this: | is the handiest shortcut in match — when three or more literals share one branch, join them instead of writing three repeated cases.
Step 3: Patterns bind variables — take a tuple apart and use it
Patterns do more than compare: they can take a value apart. A pattern can look like an unpacking assignment and bind the value's components to variables. The official example is an (x, y) coordinate:
# point is an (x, y) tuple
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")
The Tutorial specifically warns to study that one carefully: the first pattern has two literals; the next two combine a literal and a variable, and the variable binds a value from the subject; the fourth pattern captures two values, which makes it conceptually similar to the unpacking assignment (x, y) = point. The bookstore version: points on the shop's shelf map:
def where(point):
match point:
case (0, 0):
return "Origin"
case (0, y):
return f"Y={y}"
case (x, 0):
return f"X={x}"
case (x, y):
return f"X={x}, Y={y}"
case _:
raise ValueError("Not a point")
where((0, 0)) # 'Origin'
where((0, 5)) # 'Y=5'
where((3, 0)) # 'X=3'
where((3, 4)) # 'X=3, Y=4'
where("x") # raises ValueError: Not a point
where((0, 5)) returns 'Y=5' and where((3, 4)) returns 'X=3, Y=4'; handed a string "x", no pattern fits, and the final case _ raises ValueError. Order matters: (x, y) matches any two-element tuple, so it has to go last — put it first and it covers the more specific patterns (0, 0) and (0, y) completely. The wildcard _ can also sit inside a pattern, holding a place without binding anything: if you only care whether a point is on the Y axis and not what x is, write (0, _):
def on_axis(point):
match point:
case (0, _):
return "on Y axis"
case (_, 0):
return "on X axis"
case _:
return "elsewhere"
on_axis((0, 9)) # 'on Y axis'
on_axis((4, 0)) # 'on X axis'
on_axis((1, 1)) # 'elsewhere'
My judgement is this: the order of cases is "most specific first, most general last" — the pattern that accepts anything goes last; put it in the wrong order and the program raises no error, it just quietly takes the wrong branch.
Step 4: Class patterns — take an object apart by its attributes
When data is held in a class, a pattern can take it apart using the class name followed by an argument list resembling a constructor, with the ability to capture attributes into variables — by name or by position. The official example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def where_is(point):
match point:
case Point(x=0, y=0):
print("Origin")
case Point(x=0, y=y):
print(f"Y={y}")
case Point(x=x, y=0):
print(f"X={x}")
case Point():
print("Somewhere else")
case _:
print("Not a point")
The Tutorial adds two things: some built-in classes (dataclasses, for example) provide an ordering for their attributes, so positional parameters work with them; and your own classes can use positional parameters if you set the __match_args__ special attribute — set it to ("x", "y") and the four forms Point(1, var), Point(1, y=var), Point(x=1, y=var), and Point(y=var, x=1) become equivalent. The recommended way to read patterns, the Tutorial says, is as an extended form of what you would put on the left of an assignment, to understand which variables would be set to what. There is one more rule that is easy to miss: only standalone names are assigned to by a match statement; dotted names (foo.bar), attribute names (the names after x=), and class names are never assigned to. The bookstore version: the shelf coordinates held in a class:
class Point:
__match_args__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
def where_is(point):
match point:
case Point(0, 0):
return "Origin"
case Point(0, y):
return f"Y={y}"
case Point(x, 0):
return f"X={x}"
case Point():
return "Somewhere else"
case _:
return "Not a point"
where_is(Point(0, 0)) # 'Origin'
where_is(Point(0, 5)) # 'Y=5'
where_is(Point(3, 0)) # 'X=3'
where_is(Point(3, 4)) # 'Somewhere else'
where_is("nope") # 'Not a point'
With __match_args__ = ('x', 'y') set, the positional form Point(0, y) knows which attribute x and y refer to; without it, positional arguments would have nowhere to go. The Tutorial also says that once __match_args__ is set, these four forms are equivalent, all binding the y attribute to the variable var: Point(1, var), Point(1, y=var), Point(x=1, y=var), and Point(y=var, x=1). The bookstore version checks two of them:
def get_y(p):
match p:
case Point(1, var):
return var
case _:
return None
get_y(Point(1, 7)) # 7
get_y(Point(2, 7)) # None, x is not 1 so it does not match
My judgement is this: reading a class pattern is the same as reading the tuple pattern from step 3 — "take it apart by shape, bind the pieces to variables" — except that this time the pieces are an object's attributes.
Step 5: Patterns can nest — objects inside a list
Patterns can be arbitrarily nested: a list holding objects, objects holding attributes, all in one pattern. The official example is a short list of Points:
class Point:
__match_args__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
match points:
case []:
print("No points")
case [Point(0, 0)]:
print("The origin")
case [Point(x, y)]:
print(f"Single point {x}, {y}")
case [Point(0, y1), Point(0, y2)]:
print(f"Two on the Y axis at {y1}, {y2}")
case _:
print("Something else")
The bookstore version checks the official example exactly as written:
def describe_points(points):
match points:
case []:
return "No points"
case [Point(0, 0)]:
return "The origin"
case [Point(x, y)]:
return f"Single point {x}, {y}"
case [Point(0, y1), Point(0, y2)]:
return f"Two on the Y axis at {y1}, {y2}"
case _:
return "Something else"
describe_points([]) # 'No points'
describe_points([Point(0, 0)]) # 'The origin'
describe_points([Point(1, 2)]) # 'Single point 1, 2'
describe_points([Point(0, 1), Point(0, 2)]) # 'Two on the Y axis at 1, 2'
describe_points([Point(1, 1), Point(2, 2)]) # 'Something else'
An empty list, a single origin, a single ordinary point, and two points both on the Y axis each take their own branch; two points neither of which is on the Y axis fall through to case _. Nested patterns read naturally, but do not get greedy — beyond three layers, they take more effort to read than if and elif. The Tutorial offers a good way to read a pattern: treat it as an extended form of the left side of an assignment — looking at [Point(0, y1), Point(0, y2)], ask yourself "if this were the left side of an assignment, what would y1 and y2 be set to"; if you can answer that, you genuinely understand the pattern; if you cannot, do not rush to write the branch — take the pattern apart and look at one layer at a time. My judgement is this: nested patterns suit cases where "the shape itself is the answer", such as "an empty list", "a single origin", or "two points both on the Y axis"; when the shape is hard to state, deeper nesting only adds confusion.
Step 6: Guards — one more if after a case
A pattern can only look at shape, not compute a condition; to add a condition, hang an if after the case — that is called a guard. The official example:
match point:
case Point(x, y) if x == y:
print(f"Y=X at {x}")
case Point(x, y):
print(f"Not on the diagonal")
The Tutorial flags two things here: if the guard is false, match goes on to try the next case block; and value capture happens before the guard is evaluated — the x and y the guard uses are already bound, but if the guard is false, that binding does not count, and the next case binds afresh. The bookstore version: points on the diagonal:
def describe(point):
match point:
case Point(x, y) if x == y:
return f"Diagonal at {x}"
case Point(x, y):
return "Off diagonal"
describe(Point(3, 3)) # 'Diagonal at 3'
describe(Point(3, 4)) # 'Off diagonal'
For Point(3, 3), x and y are both 3, so the guard x == y is true and the first branch runs; for Point(3, 4) the guard is false, so the next case is tried, and the second case has no guard and matches directly. One detail of ordering is worth thinking through one step further: binding happens before the guard is evaluated, so the variables the guard uses are always already bound; but once the guard comes back false, those bindings are not undone — verified locally: matching (3, 4) against a case whose guard fails and falling through to case _ leaves x as 3 and y as 4 afterwards. So do not rely on "a failed guard means nothing was bound", and do not expect a same-named variable outside to still hold its old value after the match. That is also why guards should be kept simple: a guard is only a "one more check" condition, while the pattern itself decides which road to take; once a condition gets complicated, it is a sign the branch's shape has not been thought through, and splitting it into two cases or computing the condition before the match is usually cleaner. My judgement is this: a guard supplements a pattern, it does not replace one — the shape is set by the pattern and the condition is added by the guard; do not put heavy computation in a guard, it is only a "just checking" if.
Step 7: Sequence patterns — *rest, and "strings do not count as sequences"
Tuple and list patterns have exactly the same meaning, and they actually match arbitrary sequences. The Tutorial's section 4.7 lists a few key points: sequence patterns support extended unpacking, so [x, y, *rest] and (x, y, *rest) work like unpacking assignments; the name after * may also be _, so (x, y, *_) matches a sequence of at least two items without binding the remaining ones; and the important exception is that they do not match iterators or strings. The bookstore version: a delivery note whose first two items are the book title and the quantity, with remarks after them:
def first_two(value):
match value:
case [x, y, *rest]:
return (x, y, rest)
case _:
return None
first_two([1, 2, 3, 4]) # (1, 2, [3, 4])
first_two((7, 8)) # (7, 8, [])
first_two("ab") # None, strings do not take the sequence pattern
[1, 2, 3, 4] splits into 1, 2, and the rest [3, 4]; the tuple (7, 8) splits the same way; the string "ab", although it can be indexed character by character, is not accepted by a sequence pattern and falls through to case _, returning None. That exception is easy to trip over: to take a string apart, convert it to a list yourself before matching. When you do not want the rest bound at all, write *_ — it only confirms "at least two items", and throws the rest away:
def first_two_only(v):
match v:
case (x, y, *_):
return (x, y)
case _:
return None
first_two_only((1, 2, 3, 4)) # (1, 2)
first_two_only((1,)) # None, not enough elements
My judgement is this: the instinct for sequence patterns is "take it apart like a list", but Python deliberately leaves strings out — remember that one line, and it will save you a round of debugging over "why did it not match".
Step 8: Mapping patterns — take a dictionary apart by key; extra keys do not matter
A dictionary is taken apart with a mapping pattern: name the keys you want to catch, and their values are bound to variables. Tutorial section 4.7: {"bandwidth": b, "latency": l} captures the "bandwidth" and "latency" values from a dictionary; unlike sequence patterns, extra keys are ignored; and an unpacking like **rest is also supported (but **_ would be redundant, so it is not allowed). The bookstore version: a network settings dictionary:
def net_info(d):
match d:
case {"bandwidth": b, "latency": l}:
return (b, l)
case {"bandwidth": b}:
return (b, None)
case _:
return None
net_info({"bandwidth": 100, "latency": 20, "jitter": 5}) # (100, 20)
net_info({"bandwidth": 100}) # (100, None)
net_info({}) # None
The first dictionary has an extra "jitter" key and still matches, returning (100, 20); the dictionary with only "bandwidth" takes the second branch; the empty dictionary matches neither and returns None. A value in a mapping pattern can also be a literal to compare against — a sales order with a quantity of 0 means "nothing was sold":
def sale_zero(order):
match order:
case {"kind": "sale", "qty": 0}:
return "nothing to sell"
case {"kind": "sale"}:
return "some sale"
case _:
return "other"
sale_zero({"kind": "sale", "qty": 0, "title": "The Three-Body Problem"}) # 'nothing to sell'
sale_zero({"kind": "sale", "qty": 2}) # 'some sale'
And here is **rest in use:
def split_order(d):
match d:
case {"kind": k, **rest}:
return (k, rest)
case _:
return None
split_order({"kind": "sale", "title": "The Three-Body Problem", "qty": 2})
# ('sale', {'title': 'The Three-Body Problem', 'qty': 2})
My judgement is this: mapping patterns fit dictionaries whose keys are not fixed but which have a few key ones — API JSON responses, the shop's variously shaped paperwork; for a small dictionary whose keys are all fixed, plain indexing does the same job, and there is no need to reach for match just to use it.
Step 9: as captures, True/False/None, and "a bare name is a trap"
This step gathers three easy mistakes in one place. First, a subpattern can be captured whole with the as keyword: the official example case (Point(x1, y1), Point(x2, y2) as p2) binds the whole second element of the input to p2. The bookstore version:
def second_point(points):
match points:
case [Point(0, 0), Point(x, y) as p2]:
return (x, y, p2.x, p2.y)
case _:
return None
second_point([Point(0, 0), Point(3, 4)]) # (3, 4, 3, 4)
second_point([Point(1, 1)]) # None
Second, the singletons True, False, and None are compared by identity (is), while most literals are compared by equality (==) — the Tutorial's own words. So 1 does not enter case True, even though 1 == True is true:
def flag(v):
match v:
case True:
return "yes"
case False:
return "no"
case None:
return "missing"
case _:
return "other"
flag(1) # 'other'; 1 == True, but 1 is not True
flag(True) # 'yes'
flag(None) # 'missing'
Third, to use a named constant in a pattern, it must be a dotted name. The official example uses an Enum: only case Color.RED compares properly; writing case RED directly turns RED into a variable name to be bound, which matches any value — and once it sits in front, the cases after it can never be reached, and the compiler reports it immediately with SyntaxError: name capture 'RED' makes remaining patterns unreachable. The bookstore version:
from enum import Enum
class Color(Enum):
RED = 'red'
GREEN = 'green'
BLUE = 'blue'
def see(color):
match color:
case Color.RED:
return "I see red!"
case Color.GREEN:
return "Grass is green"
case Color.BLUE:
return "I'm feeling the blues :("
case _:
return "?"
see(Color("red")) # 'I see red!'
see(Color.GREEN) # 'Grass is green'
My judgement is this: of these three points, the bare name is the one most worth remembering on its own — case RED looks like comparing a colour, but it is actually binding a variable; comparisons against constants must always use a dotted name, written as Color.RED. The Tutorial's section 4.7 ends by pointing to a deeper road: for a more detailed explanation and additional examples, look into PEP 636, which is written in a tutorial format. This guide only covers what is in Tutorial section 4.7; the more advanced uses in PEP 636 (more complex guard combinations, finer points of patterns) can wait until they are needed — practise the nine steps here first, and PEP 636 will not feel difficult when you get to it.
Step 10: Wrap-up — dispatching the shop's paperwork, plus a chart of mistakes
Finally, use everything in this guide at once: the shop's paperwork comes in several shapes — sales, restocking, returns — and the mapping pattern dispatches on "kind", with case {"kind": kind} catching paperwork of a kind never seen before and case _ catching things that are not even dictionaries. One complete example:
def handle_order(order):
match order:
case {"kind": "sale", "title": title, "qty": qty}:
prices = {"The Three-Body Problem": 59.0, "Twenty Thousand Leagues Under the Seas": 39.5, "To Live": 29.0}
return round(prices[title] * qty, 2)
case {"kind": "restock", "title": title, "qty": qty}:
return f"Restock {title}: {qty} copies"
case {"kind": "return", "title": title}:
return f"Return {title}"
case {"kind": kind}:
return f"Unknown paperwork: {kind}"
case _:
return "Bad paperwork format"
handle_order({"kind": "sale", "title": "The Three-Body Problem", "qty": 2}) # 118.0
handle_order({"kind": "restock", "title": "To Live", "qty": 10}) # 'Restock To Live: 10 copies'
handle_order({"kind": "return", "title": "To Live"}) # 'Return To Live'
handle_order({"kind": "gift"}) # 'Unknown paperwork: gift'
handle_order("not a dict") # 'Bad paperwork format'
Selling 2 copies of The Three-Body Problem comes to 118.0 yuan (59.0 times 2), and selling 3 copies of Twenty Thousand Leagues Under the Seas comes to 118.5 yuan (39.5 times 3); restocking, returns, unknown paperwork, and wrongly formatted paperwork each take their own branch. Writing the same five roads with if and elif would mean writing order["kind"] == ... five times, with the catch-all easy to forget; match puts the "shape" first, so it is obvious at a glance which road each kind of paperwork takes. Try it yourself: add one more kind of paperwork to handle_order — {"kind": "discount", "title": "The Three-Body Problem", "rate": 0.8}, meaning The Three-Body Problem at 20% off, returning the discounted unit price of 47.2 yuan. Check your work against four points: does the new case sit before or after case {"kind": kind}, and what happens if it is in the wrong place; is "rate" a variable to bind or a literal to write; will a sales order with a quantity of 0 stray into another branch; and will passing in a plain string reach case _? Once all four are clear, the dispatch logic of match is genuinely yours: whether the input is paperwork, messages, or JSON from an API, the habit is the same — look at the shape first, then write the branches.
Finally, the chart of mistakes for this guide. Example: the fictional Morning Light Bookstore bookkeeping script, in its eighth month of learning Python, made 100 match-related mistakes, distributed as follows. The most common mistake, at the top of the chart, is forgetting to write case _, so that no match means silently doing nothing.

Looking back over the ten steps, this guide really only taught three things. First, match dispatches by shape: only the first matching branch runs, and if nothing matches, nothing happens, so a case _ catch-all must not be skipped; patterns go most specific first and most general last, and putting them in the wrong order raises no error — it just takes the wrong road. Second, patterns can take things apart: tuples, lists, dictionaries, and objects can all be split by shape with their pieces bound to variables; sequence patterns do not accept strings, and mapping patterns ignore extra keys; True, False, and None are compared by identity, and named constants must be written as dotted names. Third, a guard is a supplement: the shape is set by the pattern, the condition is added by the guard, and binding happens before the guard is evaluated. The next guide is reserved for virtual environments and packaging: getting the bookkeeping script running on another computer in the shop — how to create a venv, how to lock dependencies, how to build a package — and when that happens, this guide's match dispatch will move into the new environment along with it, running just the same in a different place.
Comments (0)
Sources
Related articles
Adding a book parses to price=59.9, count=3, total 179.7; listing by price takes 2; four errors all exit with code 2; --pri abbreviates, and no subcommand parses to None. Python 3.12.3 stdlib, measured.
Building stock of 2000 books moves current memory from 0.3 KiB to 582.7 KiB; subtracting two snapshots, the biggest line is line 85 at 568.1 KiB and 9699 blocks; getsizeof sees only 15.8 KiB, and clearing brings the line back to 0.0 KiB. Python 3.12.3 stdlib, measured.
Port 8000 in code, 8080 in the config file, 9090 from the environment: each layer changes only its own keys, and the last one wins. Defaults plus INI plus env vars, bool('False') is True, and a missing key should fail at startup. Python 3.12.3 stdlib only.