1. Home
  2. Blog
  3. Software Development

Software Development

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.

9 min read
Python match case: 12 pattern matching examples, guards and traps

Key takeaways

  • 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 binds direction in 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 if is 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
Software Development

Content Security Policy Explained: Nonces, strict-dynamic and Report-Only

Content security policy explained: nonces, strict-dynamic, Report-Only, eval, image and style rules, tested in a real browser, plus a strict…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Databases & SQL

Gaps and Islands in SQL: Find Streaks and Missing Ranges

Gaps and islands in SQL: find login streaks and missing ranges with ROW_NUMBER, DENSE_RANK, LAG and LEAD, plus the duplicate…

Read article →
Databases & SQL

INSERT INTO SELECT in SQL: Copy Rows Between Tables Safely

INSERT INTO SELECT in SQL: copy rows between tables with chosen columns, joins and summaries, avoid duplicates on reruns, upsert,…

Read article →
Software Development

JavaScript Proxy Explained: All 13 Traps, Reflect and Real Use Cases

JavaScript Proxy explained: all 13 traps, Reflect, validation, defaults, hidden keys, revocable proxies, private field problems and the speed cost,…

Read article →
Software Development

Python Threading Explained: Threads, Locks, Queues and the GIL, Timed

Python threading explained and timed: threads vs processes, the GIL, a real race condition, locks, ThreadPoolExecutor, queues, events and daemon…

Read article →
Software Development

Python Match Case: 12 Pattern Matching Examples, Guards and Traps

Python match case explained with 12 tested examples: literals, OR patterns, guards, sequences, dictionaries, classes, the capture trap and speed…

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
Software Development

301 vs 302 Redirect: Differences, SEO Impact, 307 and 308

301 vs 302 redirect: the differences, SEO impact, 307 and 308, method changes, redirect chains and loops, all tested on…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Databases & SQL

SQL Random Rows: How to Select Random Rows Fast and Fairly

SQL random rows: how to select random rows fast and fairly, timing ORDER BY RANDOM, offsets and ID jumps, and…

Read article →
Databases & SQL

SQL Median: 4 Ways to Calculate the Median, With Tested Queries

SQL median explained: four tested ways to calculate the median, including percentile functions, window ranks, offsets and per group medians.

Read article →
Software Development

JavaScript Regex Explained: Patterns, Flags, Groups and Pitfalls

JavaScript regex explained: literals, flags, groups, named groups, lookarounds, matchAll, replace and the catastrophic backtracking trap, tested in Node.

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →
Databases & SQL

SQL ROUND Function: Decimals, Ties, CEIL, FLOOR and Money

SQL ROUND explained with tested queries: decimals, tie rules, the 2.675 float trap, negative digits, CEIL, FLOOR, truncation and rounding…

Read article →
Databases & SQL

Recursive CTE in SQL: Hierarchies, Paths, Series and Cycles

Recursive CTE in SQL explained with tested queries: org charts with levels and paths, walking up a tree, team sizes,…

Read article →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →
Artificial Intelligence

K Nearest Neighbors (KNN) Explained: How It Works, With Python Code

K nearest neighbors explained: the KNN algorithm, a from-scratch NumPy version, choosing k, feature scaling, distance metrics, regression and vector…

Read article →
DevOps

Git Rebase Interactive: Squash, Fixup, Reword and Autosquash

Git rebase interactive explained step by step: pick, reword, squash, fixup, edit, drop, autosquash, conflicts and undoing a rebase with…

Read article →
Software Testing

Alpha vs Beta Testing: Key Differences, Exit Criteria and Checklist

Alpha vs beta testing compared: who tests, what each phase finds, entry and exit criteria, how to run a beta,…

Read article →
Test Automation

Pytest Monkeypatch: 10 Tested Examples for Env Vars, Time and APIs

Pytest monkeypatch explained with 10 passing tests: environment variables, functions, config, time, sleeps, paths, blocking the network and the wrong-target…

Read article →
Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →