match and case

Matching a value against patterns rather than testing it with a chain of conditions - including patterns that destructure as they match.

Overview

Matching a value against patterns rather than testing it with a chain of conditions - including patterns that destructure as they match.

In this guide
  1. The tidy version of an if-chain
  2. What it actually adds
  3. Guards
  4. Why it was added
  5. Patterns you will use
  6. The two rules to remember
  7. Version, and whether to use it
  8. Destructuring in one step
  9. The bare name that swallows everything
  10. Not exhaustive, and what that means
  11. Guards, classes and the shapes worth knowing
  12. A worked example: a small command parser
  13. Enums, the natural partner
  14. Questions people ask about match and case
  15. match and case: recap in one screen

match_basics.py

match_basics.py Python 3
Output

                    

match_structure.py

match_structure.py Python 3
Output

                    

Worth knowing

case _: is the default. Without it, no match simply falls through and nothing happens.
| matches several literals in one case.
Patterns bind as they match: case {"x": x} pulls x out for you.
A bare name matches everything and binds. Use case Colour.RED or case 200, not a lone variable.

match and case: A Practical Guide

match tests a value against patterns rather than rules. For plain literals it's a tidier if-chain. For structured data it's a thing an if-chain can't do at all. The pattern takes the value apart while matching it.

The tidy version of an if-chain

match status:
    case 200:
        return "ok"
    case 500 | 502 | 503:
        return "server error"
    case _:
        return "unhandled"

| groups options, _ is the default. The first matching case wins and the rest are skipped. There is no fall-through and no break.

If this were all match did it would be barely worth the keyword. The page prints an if-chain beside it that does the same thing on the same inputs.

The real reason match exists is structural pattern matching, which goes far beyond comparing values. A case can test the shape of a value: whether it is a tuple with two elements, a dictionary with certain keys, or an object with certain attributes. That ability turns complex nested if checks into flat, readable patterns.

Consider parsing a command that arrives as a tuple. Without match, you write an if that checks the length, then checks the first element, then checks the types of the remaining elements. With match, you write case ("move", int(x), int(y)): and all three checks happen in one line. The values are bound to x and y at the same time.

Guards add conditions to a pattern. case int(n) if n > 0: matches only positive integers. The pattern checks the type and the guard checks the value. Together they replace a type check followed by a value check, collapsing two levels of indentation into one.

The syntax arrived in Python 3.10, so it is newer than most of the language. Code that needs to run on older versions cannot use it. But on 3.10 and above, it handles command dispatching, protocol parsing, and any branching logic that depends on the structure of data rather than just its value.

This page covers simple value matching, the wildcard pattern, structural patterns with destructuring, guards, and how match compares to an if/elif chain.

What it actually adds

case {"type": "click", "x": x, "y": y}:

This matches a dict that has a type of "click". In the same breath binds x and y to the values it found. One line replaces a type check, two key checks and two lookups. And it can't go out of step with itself the way that sequence can.

The same applies to sequences:

case [first, *rest]:

matches any list and splits it into head and tail as it goes.

Guards

A pattern can carry a rule:

case int() if n < 0:

The pattern narrows the shape, the guard narrows the value. Together they express "an int. A minus one" in the place where you're already looking.

Why it was added

Python resisted a switch statement for decades on the grounds that a chain of if/elif already did the job, and for checking a value against a few constants that arg still holds. match wasn't added to replace those.

It was added for structural pattern matching: inspecting the *shape* of data and pulling it apart in the same step. The code it replaces is a stack of isinstance checks, key lookups and length tests, written in a exact order, where getting the order wrong or losing a check makes a bug that only appears on unusual input. That pattern shows up constantly in any of it that handles parsed JSON, events, commands or syntax trees.

Once you see it as "destructure and dispatch" rather than "switch", the design choices stop looking strange.

Patterns you will use

Literal patterns match constants. Sequence patterns like [a, b] or [first, *rest] match lists and tuples of the right shape and bind the parts. Mapping patterns like {"type": "click", "x": x} match dicts that *hold* those keys - extra keys are allowed. This Is what makes them handy against real payloads that carry more than you care about.

Class patterns match an instance and can pull fields out of it: case Point(x=0, y=y) matches a Point on the y-axis and binds y. Mixed with a guard, that covers a surprising amount of dispatch logic in one readable block.

The two rules to remember

A bare name captures rather than checks, and it matches all. If you want to compare against a constant you've stored a place, it must be a dotted name - case Status.OK - or a literal. This is the single most common match bug, and the failure mode is silent: the first such case swallows each value and the ones below it never run.

And match isn't exhaustive. If nothing matches and there's no case _, the statement simply does nothing and run continues. Coming from languages where the compiler insists on exhaustiveness, that is worth remembering, because a missing case here is a quiet no-op rather than an error.

Version, and whether to use it

match needs Python 3.10. If your code has to run on any of it older, the if/elif version is the only option, and for two or three literal checks it's the better one even so: shorter, universally understood, and with none of the capture-pattern sharp edges.

Destructuring in one step

The arg for match isn't tidiness, it's that the pattern checks the shape and pulls the pieces out in the same breath:

events = [
    {"type": "click", "x": 10, "y": 20},
    {"type": "key", "key": "a"},
    {"type": "scroll", "amount": 3, "extra": "ignored"},
    "not a dict",
]

for e in events:
    match e:
        case {"type": "click", "x": x, "y": y}:
            print("click at", x, y)
        case {"type": "key", "key": k}:
            print("key", k)
        case {"type": t}:
            print("other event:", t)
        case _:
            print("unrecognised:", e)
click at 10 20
key a
other event: scroll
unrecognised: not a dict

Three things are worth noticing. The scroll event carries an extra key that no pattern mentions, and it still matches. Mapping patterns check that the named keys are *present*, not that they're the only ones, which is what makes them usable against real payloads.

The string falls through to case _, because a mapping pattern doesn't match a non-mapping. Written with if, that safety would have been an clear isinstance(e, dict) that somebody has to note.

And x, y, k and t are bound by the match itself. The equal if-chain needs a key check and a lookup for each, in the right order, with the lookups repeating what the checks just established.

The bare name that swallows everything

A bare name in a pattern doesn't compare against that name. It's a capture pattern: it matches any of it at all and binds the name to what it caught.

Python protects you from the obvious form of the mistake. Writing a capture before other cases is a compile-time error, and the message is unusually direct:

SyntaxError: name capture 'OK' makes remaining patterns unreachable

What it can't protect you from is the same mistake in the last spot, where there are no unreachable patterns to complain about:

OK = 200

for status in [200, 404, 500]:
    match status:
        case 404:
            print(status, "not found")
        case OK:
            print(status, "matched OK")

print("OK is now", OK)
200 matched OK
404 not found
500 matched OK
OK is now 500

500 "matched OK", because case OK: matched all the earlier case did not. And the constant is gone. OK was rebound each time the capture fired, so after the loop it holds 500.

The fix is a dotted name. This Is a value pattern and does compare:

class Status:
    OK = 200

for status in [200, 404, 500]:
    match status:
        case 404:
            print(status, "not found")
        case Status.OK:
            print(status, "matched OK")
        case _:
            print(status, "unhandled")
200 matched OK
404 not found
500 unhandled

This is why enums pair so on its own with match: case Colour.RED is unambiguous, and an enum gives you the dotted form for nothing. Literals work too. It's only bare names that capture.

Not exhaustive, and what that means

Languages that popularised pattern matching often check that each possible case is handled, and refuse to compile if one is missing. Python doesn't.

If no case matches and there's no case _, the match statement simply does nothing and run continues on the next line. No exception, no warning. A value that falls through leaves no trace, and the symptom appears later as a result that was never found.

That makes case _ more key than a default clause often is. Ending with one that raises — or at min logs the unhandled value — converts a silent no-op into a thing you can find:

        case _:
            raise ValueError(f"unhandled event: {event!r}")

The same applies inside a function returning a value: a match where each case returns will return None for an unmatched value, which then travels a place else before failing. Making the fallthrough clear is the habit worth forming from the first match you write.

Guards, classes and the shapes worth knowing

Beyond literals and mappings, three pattern kinds cover most real use.

Sequence patterns match lists and tuples structurally. case [x] matches a one-item sequence, case [first, *rest] matches any non-empty one and splits it, case [] matches empty. They don't match strings, which is deliberate — a string is a sequence of characters and matching it as one is almost never what anybody means.

Class patterns match an instance and can read fields: case Point(x=0, y=y) matches a Point whose x is zero and binds its y. Dataclasses and named tuples support the spot-based form, case Point(0, y), via __match_args__.

Guards attach a rule to a pattern with if: case [x, y] if x == y matches a two-item sequence whose items are equal. The pattern narrows the shape, the guard narrows the values, and a guard that fails lets the next case try. It doesn't abandon the whole match.

The combination is what makes the feature earn its keyword. "A two-element list of ints where the first is minus" is one line, and the if-chain equal is a length check, two isinstance calls and a check in a exact order.

A worked example: a small command parser

each pattern kind in one function, doing the job match was added for:

def run(command):
    match command.split():
        case ["quit"] | ["exit"]:
            return "goodbye"
        case ["add", *items] if items:
            return f"adding {len(items)}: {', '.join(items)}"
        case ["get", key]:
            return f"looking up {key}"
        case [verb, *_]:
            return f"unknown command: {verb}"
        case _:
            return "say something"


for line in ["quit", "add pen pad", "get colour", "add", "spin around", ""]:
    print(f"{line!r:16} -> {run(line)}")
'quit'           -> goodbye
'add pen pad'    -> adding 2: pen, pad
'get colour'     -> looking up colour
'add'            -> unknown command: add
'spin around'    -> unknown command: spin
''               -> say something

Read the cases in order. The first uses | for options, both of which are one-word sequences. The second matches add followed by any number of items and binds them, with a guard rejecting the case where there are none — which is why bare "add" falls through to the catch-all verb case rather than reporting "adding 0". The third needs just two words, so get with two args wouldn't match it.

The fourth is the notable one: [verb, *_] matches any non-empty list, binds the first word and discards the rest with _. The last handles the empty string, whose split() gives []. This No sequence pattern with a needed element can match.

Written as an if-chain, each of those turns a length check plus an index plus a check, in an order that has to be right. Here the shape and the extraction are the same formula, and a case that doesn't fit simply does not match.

Enums, the natural partner

The capture-pattern trap has a structural fix rather than a discipline one: use an enum, and the problem can't arise.

An enum member is always reached through a dotted name — Colour.RED, Status.NOT_FOUND — which makes each ref a value pattern by build. There's no way to accidentally write the bare form, because the bare form doesn't name any of it.

Two further gains follow. The set of valid values is written down in one place, so a reader can see what the match is dispatching over without gathering the cases. And because the members are objects rather than ints, a typo is an AttributeError at the point of the mistake rather than a case that silently never fires.

This is the shape most match statements in well-organised code take: an enum or a set of classes defining the options, and a match that handles each one and ends with a case _ that raises. Between them, the two make the set of cases clear and the missing case loud. Getting back most of what the exhaustiveness checking of other languages gives, without the language doing it for you.

Questions people ask about match and case

Is there fall-through like C's switch? No. The first matching case runs and the statement ends. No break is needed or allowed.

Can I match on types? Yes, with a class pattern: case int(): matches any int. Note the brackets. case int: without them is a value pattern checking against the type object.

Does a mapping pattern need exact keys? No, extra keys are allowed. Use **rest to capture them.

Can I bind the whole value and its parts? Yes, with as: case {"type": "click"} as event.

Why does case [x] not match a string? Sequence patterns on purpose exclude str, bytes and bytearray.

Is match a keyword now? It's a soft keyword, so existing code using match as a variable name still works.

Should I convert my if-chains? Only where they're inspecting shape. For checking one value against a few constants, the chain is fine and runs on older Python.

Can a guard ref names bound by the pattern? Yes, and that is the usual reason to write one. The pattern binds, then the guard tests what it bound.

Is match faster than an if-chain? For literals they're close. For structural patterns it's often faster than the equal checks, and speed isn't the reason to choose it.

Can I match against a set of allowed values? Use | between literals in one case, or a guard with in when the collection is built elsewhere.

match and case: recap in one screen

  • match tests patterns, not rules. The pattern checks shape and binds parts in one step.
  • A bare name captures and matches all. Use a literal or a dotted name to compare against a constant.
  • Mapping patterns allow extra keys. Sequence patterns never match strings.
  • Nothing is exhaustive: an unmatched value falls through silently, so end with case _ that raises or logs.
  • Reach for it when inspecting the shape of data, and keep if/elif for a few literal checks. needs Python 3.10.

Check yourself

0 of 3

Answer without scrolling back up.

  1. What does a bare `case status:` do?

  2. What happens when no case matches and there is no `case _`?

  3. `case {"type": "click", "x": x}` does what beyond matching?

Cheat sheet

match and case

Use match/case to test a value against patterns instead of chains of if/elif, and see how destructuring pulls values out of the match.

PYTHON · vizlearn.in/python/match_and_case.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.