Pattern matching with match/case
Replace long if/elif chains with readable match statements where they fit.
By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.
In short
match/case (Python 3.10+) compares one value against a list of patterns and runs the first that fits. It can match literals, unpack tuples and check object types, often replacing long if/elif chains.
Explained simply
match looks at one value and compares it with a list of shapes, called patterns. The first case whose pattern fits runs, and the rest are skipped. Think of a sorting machine with slots of different shapes: each parcel drops into the first slot it fits.
It is more than a switch statement. A pattern can check an exact value, the structure of a list or tuple, the keys of a dictionary, or the type of an object, and it can pull pieces out into variables in the same step.
match needs Python 3.10 or newer. End the list with case _: as a catch-all, like else. If nothing matches and there is no catch-all, nothing happens and no error is raised.
It is not a replacement for every if. match shines when you branch on the shape of data: commands typed by a user, JSON messages from an API, tokens in a parser. For range checks like score >= 90, a plain if/elif stays clearer.
Press Play on a diagram to walk through it one step at a time.
- 1Evaluate subject
match command: computes the value once
- 2Try case 1
Pattern fits? Bind names and run its block
- 3Try next case
Only if earlier patterns did not fit
- 4case _
Wildcard: matches anything left over
- 5Done
At most one case block runs
- One subject, many shapes
- Unpacking lists, dicts or objects
- Commands, events, parsed tokens
- Several values share one branch
- Range checks like x >= 90
- Conditions on different variables
- Only two or three simple branches
- Code must run on Python before 3.10
In depth
The pattern kinds
Literal patterns match exact values: numbers, strings, None, True and False. A capture pattern is a bare name like x; it matches anything and binds the value to that name. The wildcard _ also matches anything but binds nothing. A value pattern is a dotted name like Color.RED or HTTPStatus.OK; it is compared with ==.
Structural patterns go further. Sequence patterns like [x, y] or [first, *rest] match lists and tuples by length and position. Mapping patterns like {"type": "click", "x": x} match dicts that contain those keys. Class patterns like Point(x=0, y=y) check the type, then the attributes.
You can combine patterns. An OR pattern, 200 | 201 | 204, matches any of the alternatives. An as pattern, case [x, y] as pair, binds the whole matched value too. Patterns nest freely, so one case can describe a dict that holds a list of numbers.
- Literal
- case 404:
- case "quit":
- case None:
- Capture and wildcard
- case x: binds anything
- case _: matches, binds nothing
- Value
- case Color.RED:
- Dotted names compare with ==
- Sequence
- case [x, y]:
- case [first, *rest]:
- Mapping
- case {"type": "click"}:
- Extra keys are ignored
- Class
- case Point(x=0, y=y):
- case str(s):
Guards, order and unreachable cases
A guard adds an if to a case: case int(n) if n < 0:. The pattern is tried first; if it fits, the guard is checked; if the guard is False, Python simply moves on to the next case. Guards let you mix structure checks with value checks such as ranges.
Cases are tried strictly top to bottom, so put specific cases before general ones. Python helps a little: a case that can match anything, such as case _: or case x:, followed by more cases is a SyntaxError ("makes remaining patterns unreachable"), because those later cases could never run.
Unlike switch in C or Java, there is no fall-through. Exactly one case block runs, or none, and you never need break. To share a body between several values, use an OR pattern instead of stacking cases.
Sequence and mapping patterns in detail
A sequence pattern matches lists, tuples and other sequences, but deliberately not strings or bytes, so case [a, b] will not split "ab" into letters. The length must match exactly unless you use a star: [first, *rest] needs at least one item, and [*_, last] grabs the final one. Matching command.split() against ["go", direction] is a neat way to parse simple text commands.
A mapping pattern matches any dict that has at least the listed keys with matching values; extra keys are ignored, which is exactly what you want for JSON from an API. Values inside can be any pattern, including type checks: {"user": {"name": str(name)}} matches only when name is really a string.
These structural checks replace a lot of defensive code: isinstance, len and key in checks that you would otherwise write by hand before touching the data.
- 1Is it a mapping?
Lists, strings and None fail here
- 2Has key "type"?
Missing key: try the next case
- 3Value is "move"?
Compared with ==
- 4Has key "x" with an int?
int(x) checks the type
- 5Bind x and run
Extra keys never matter
Class patterns and their traps
case Point(x=0, y=y): first checks isinstance(subject, Point), then compares subject.x with 0 and binds subject.y to y. Keyword sub-patterns work with any class. Positional sub-patterns such as Point(0, y) need the class to define __match_args__, which dataclasses create for you automatically.
Built-in types have a shortcut: int(n), str(s), float(f) and similar check the type and bind the whole value. Watch the order with numbers: bool is a subclass of int, so case int(): also matches True. Put case bool(): first if you treat them differently.
The classic trap is constants. case MAX: with a bare name is a capture pattern: it matches everything and overwrites MAX. Use a dotted name (Limits.MAX, an Enum member) or a literal value. Linters and the SyntaxError for unreachable cases often catch this, but not always.
Learn it in 3 short steps
About 20m each. Track them with a timer in your plan.
- 1Write a basic match/case statement~20m
- 2Match on literals, tuples and classes~20m
- 3Refactor an if/elif chain to match~20m
Key points
- Cases are tried top to bottom; the first matching pattern wins.
- case (x, y): unpacks a 2-item sequence and binds x and y.
- case _: is the catch-all, like else.
- Combine options with |, and add conditions with a guard: case n if n < 0.
Key terms
Tap a card to flip it. 0/5 known
Examples
def handle(command):
match command.split():
case ["quit"]:
return "Bye"
case ["go", direction]:
return f"Going {direction}"
case ["add", x, y]:
return int(x) + int(y)
case _:
return "Unknown command"
print(handle("go north")) # Going north
print(handle("add 2 3")) # 5
print(handle("dance")) # Unknown commandHandling JSON-like events from a web app
A front end sends dicts such as {"type": "click", "x": 3, "y": 7, "time": 1}. Step 1: the first case matches clicks only when x and y are ints, and binds them. Step 2: an OR pattern catches the two closing keys. Step 3: any other key event binds its key name. Step 4: any dict with a type is acknowledged. Step 5: case _ handles anything that is not an event at all. Without match this would need several isinstance, in and len checks.
def handle(event):
match event:
case {"type": "click", "x": int(x), "y": int(y)}:
return f"Click at {x},{y}"
case {"type": "key", "key": "Escape" | "q"}:
return "Closing"
case {"type": "key", "key": str(k)}:
return f"Key {k}"
case {"type": t}:
return f"Ignored event {t!r}"
case _:
return "Not an event"
print(handle({"type": "click", "x": 3, "y": 7, "time": 1})) # Click at 3,7
print(handle([1, 2])) # Not an eventRefactoring an HTTP status chain
The old code was if status == 200 or status == 201 or status == 204, then more elifs. Step 1: OR patterns group the success codes and the redirect codes on one line each. Step 2: 404 is a simple literal. Step 3: a class pattern with a guard handles every 5xx code without listing them. Step 4: case _ replaces the final else. Each line now says what it means, and adding a code is a one-word change.
def describe(status):
match status:
case 200 | 201 | 204:
return "Success"
case 301 | 302 | 307 | 308:
return "Redirect"
case 404:
return "Not found"
case int(code) if 500 <= code < 600:
return f"Server error {code}"
case _:
return "Other"
print(describe(204), describe(503), describe(418))
# Success Server error 503 OtherQuick reference
- match needs Python 3.10 or newer; check with python3 --version
- case 200 | 201 | 204: an OR pattern matches any of the alternatives
- case [first, *rest]: matches a list or tuple with at least one item
- case {"type": "click"}: matches any dict with that key and value; extra keys are ignored
- case Point(x=0, y=y): checks the type, then compares and binds attributes
- case Color.RED: dotted names compare values; a bare name always captures
- Sequence patterns never match strings, so case [a, b] ignores "ab"
- No case matched and no case _? Nothing runs and no error is raised
Common mistakes
- case RED: with a bare name captures anything; use a dotted name like Color.RED.
- Using match on Python older than 3.10, which gives a SyntaxError.
- Rewriting simple two-branch ifs as match where if is clearer.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write day_type(day) using match. Return "weekend" for "sat" or "sun", "weekday" for the other five short names, and "unknown" for anything else.
- Exercise 2medium
Write where(p) that describes a point given as a 2-item tuple: "origin" for (0, 0), "on the x-axis at X", "on the y-axis at Y", "at X, Y" otherwise, and "not a point" for anything that is not a 2-item sequence.
- Exercise 3hard
Build a tiny shopping-list shell with the commands add ITEM [QTY], remove ITEM, show and quit. QTY defaults to 1 and must be digits. Match on input().split() and print a help line for anything else.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is match/case the same as switch in other languages?
- It can do everything a switch does, and it also unpacks lists, dicts and objects. There is no fall-through between cases, so you never write break.
- Is match faster than if/elif?
- Not in a way that matters for normal code. Choose it for readability when you check one value against many shapes.
- Why does my case catch everything?
- A bare name such as case status: is a capture pattern that matches any value. Compare against constants with dotted names like Status.OK or with literal values.
- Can match check the type of a value?
- Yes, with class patterns such as case int(): or case str(s):. Put case bool() before case int(), because True and False are ints too.