Python Match Case: 12 Pattern Matching Examples, Guards and Traps
Python match case, added in Python 3.10, is much more than a switch statement. It can unpack lists, pull values out of dictionaries, check object types and attributes, and add conditions with guards. Here are 12 tested examples, the capture trap that silently matches everything, and a timing comparison with if and elif.
- Python match case compares a value against patterns from top to bottom and runs only the first one that matches.
- Patterns can destructure:
case ["go", direction]checks the shape and bindsdirectionin one step. - A bare name such as
case NOT_FOUND:is a capture, not a comparison. It matched 200 in our test and overwrote the variable. - For simple value checks, our if/elif version was faster: 88 versus 152 microseconds per 1,000 calls.
Before Python 3.10, branching on the shape of data meant chains of if isinstance(...), len() checks and manual unpacking. Python match case, formally called structural pattern matching (PEP 634, with the tutorial in PEP 636), replaces those chains with patterns that describe what the data should look like. It is the closest thing Python has to a switch statement, but it goes much further.
Every example below ran on Python 3.13.6, and the outputs are copied from the run.
The match case syntax
match subject:
case pattern1:
...handle it
case pattern2 if condition:
...handle it
case _:
...fallback
Python evaluates the subject once, then tries each case in order. The first pattern that matches wins, and the rest are skipped. There is no fall-through as in C, so you never need break. If nothing matches and there is no case _, the statement simply does nothing: no error is raised.
Examples 1 to 3: literals, OR patterns and the wildcard
def http(status):
match status:
case 200 | 201 | 204: return "ok"
case 301 | 302: return "redirect"
case 404: return "not found"
case int(n) if 500 <= n < 600: return "server error"
case _: return "other"
[http(s) for s in (200, 302, 404, 503, 418)]
# ['ok', 'redirect', 'not found', 'server error', 'other']
Literal patterns compare with == (and with is for None, True and False). The | operator combines alternatives, and _ is the wildcard that matches anything without binding a name. Put it last: it is the default branch.
Example 4: guards add conditions
The fourth case above, case int(n) if 500 <= n < 600, is a guard. The pattern int(n) checks the type and binds the value to n, then the if clause must also be true. If the guard fails, Python moves on to the next case, which is why 418 fell through to "other". Guards are how you express ranges, comparisons and any logic that a pattern alone cannot describe.
Examples 5 and 6: sequence patterns and star capture
def cmd(text):
match text.split():
case ["go", direction]: return f"move {direction}"
case ["take", *items] if items: return f"take {items}"
case ["quit" | "exit"]: return "bye"
case []: return "empty"
case _: return f"unknown {text!r}"
# go north -> move north
# take sword shield -> take ['sword', 'shield']
# exit -> bye
# (empty string) -> empty
# dance -> unknown 'dance'
This is where match case beats any switch statement. ["go", direction] matches only a two-item list whose first item is "go", and binds the second item. *items collects any remaining items into a list, like star unpacking in assignments. A nested OR pattern, ["quit" | "exit"], handles synonyms. Writing this parser with if statements would need length checks and indexing on every branch.
Examples 7 and 8: dictionary (mapping) patterns
def event(e):
match e:
case {"type": "click", "x": x, "y": y}: return f"click {x},{y}"
case {"type": "key", "key": str(k)}: return f"key {k}"
case {"type": t, **rest}: return f"{t} extra={rest}"
event({"type": "click", "x": 1, "y": 2, "btn": "L"}) # click 1,2
event({"type": "key", "key": "a"}) # key a
event({"type": "scroll", "dy": -3}) # scroll extra={'dy': -3}
Mapping patterns check that the listed keys exist and match, and they ignore extra keys: the click event had a "btn" key and still matched. That makes them ideal for JSON from APIs, where new fields appear over time. Use **rest to capture everything you did not name. For more on working with dicts, see our Python dictionary guide and, for parsing API payloads, our Python JSON guide.
Examples 9 and 10: class patterns
@dataclass
class Point:
x: int
y: int
def where(p):
match p:
case Point(x=0, y=0): return "origin"
case Point(x=0, y=y): return f"on y axis at {y}"
case Point(x, y) if x == y: return "diagonal"
case Point(): return "somewhere"
# Point(0,0) origin | Point(0,5) on y axis at 5
# Point(3,3) diagonal | Point(2,7) somewhere
A class pattern first checks isinstance, then matches attributes. Keyword form, Point(x=0, y=y), works on any class. Positional form, Point(x, y), needs a __match_args__ attribute that says which attributes map to which positions; dataclasses generate it for you, which is why example 10 worked with no extra code. Point() with no arguments is just a type check.
Example 11: type checks with built-in classes
def types(v):
match v:
case bool(): return "bool"
case int(): return "int"
case float() | complex(): return "number"
case str() as s if not s: return "empty str"
case str(): return "str"
case [int(), *_]: return "list starting with int"
case (a, b): return f"pair {a},{b}"
case None: return "None"
# True bool | 3 int | 2.5 number | "" empty str | "hi" str
# [1, 2] list starting with int | ("a","b") pair a,b | None None
Order matters here. bool is a subclass of int, so if case int() came first, True would be reported as an int. The as keyword binds the whole matched value to a name while still checking its type. Type checks like these pair well with type hints, which describe the same shapes for static checkers.
Example 12: matching constants with dotted names
from http import HTTPStatus
def dotted(code):
match code:
case HTTPStatus.NOT_FOUND: return "404 via dotted name"
case _: return "no"
dotted(404), dotted(200) # ('404 via dotted name', 'no')
A name with a dot in it, such as HTTPStatus.NOT_FOUND or Color.RED, is treated as a value to compare against. That is the correct way to match named constants, and it works beautifully with Python enums. Which brings us to the most common bug.
The capture trap: a bare name matches everything
NOT_FOUND = 404
def trap(code):
match code:
case NOT_FOUND:
return f"matched, NOT_FOUND is now {NOT_FOUND}"
trap(200) # 'matched, NOT_FOUND is now 200'
A bare name in a pattern is a capture pattern: it matches any value and assigns it to that name. So case NOT_FOUND: did not compare with 404 at all. It matched 200 and overwrote the variable. Python catches the worst version at compile time. When a capture pattern is followed by more cases, we got:
SyntaxError: name capture 'y' makes remaining patterns unreachable
But when the capture is the last case, as above, there is no warning at all. The fix is to use a dotted name (an enum member or module.CONSTANT), a literal, or a guard such as case code if code == NOT_FOUND.
Tip: if a constant must be matched, put it in an Enum or a class. Dotted names are always compared, never captured.
Strings are not treated as sequences
types("ab") # 'str'
types(["a", "b"]) # 'pair a,b'
A two-character string did not match the (a, b) sequence pattern, while a two-item list did. Sequence patterns deliberately exclude str, bytes and bytearray, so "ab" is never unpacked into characters by accident. Tuples and lists are interchangeable in patterns: (a, b) and [a, b] mean the same thing.
Is match case faster than if and elif?
We ran the HTTP status classifier from example 1 against an equivalent if/elif chain, 1,000 calls per run, best of five:
| Version | Time per 1,000 calls |
|---|---|
match with literals, OR and a guard |
152.2 microseconds |
if / elif with in tuples |
87.8 microseconds |
Match case is not a jump table. Python still tests patterns one by one, and here the if version was about 1.7 times faster. For a request handler the difference is negligible, a fraction of a microsecond per call, but do not switch to match expecting a speed-up. Choose it for readability when you are checking structure, not for performance. If you need a fast lookup of many literal values, a dictionary mapping is still the quickest option.
When to use match case, and when not to
- Use it for parsing commands, tokens and messages, handling JSON with several shapes, walking syntax trees, and dispatching on a mix of types.
- Use it when each branch needs to pull values out of the data; destructuring is the real benefit.
- Skip it for two or three simple comparisons, where
ifis shorter and familiar to every reader. - Skip it if your code must run on Python 3.9 or older, where it is a syntax error.
Match does not replace error handling either: if a branch must reject bad input, raise an exception from the fallback case, as described in our exception handling guide.
Final thoughts
Python match case shines when data has structure: lists with a command word, dictionaries from an API, dataclasses with a few fields. Learn the pattern types (literal, capture, wildcard, OR, sequence, mapping and class), add guards for conditions, and remember the two traps: a bare name captures instead of comparing, and bool must come before int. Used for structure rather than for simple values, it makes branching code shorter and much easier to read.
Frequently asked questions
Does Python have a switch statement?
Since Python 3.10 the match statement does the job of a switch, and more. Each case is a pattern, the first match wins, and there is no fall-through, so no break is needed.
What Python version supports match case?
Python 3.10 and newer. On Python 3.9 or older, the match statement is a syntax error, so use if and elif chains or a dictionary lookup instead.
Why does my case with a variable name match everything?
A bare name is a capture pattern. It matches any value and assigns it to that name. To compare against a constant, use a dotted name such as an enum member, a literal, or a guard.
What does the underscore mean in match case?
The underscore is the wildcard pattern. It matches any value without binding it, so case _ at the end works as the default branch.
Is match case faster than if elif?
Not in our test. A classifier written with match took 152 microseconds per 1,000 calls versus 88 for the if and elif version. Choose match for readability when checking structure.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.