Structural pattern matching: match-case

`match`/`case` from Python 3.10: literal, capture and wildcard patterns, sequence, mapping and class patterns, OR-patterns, `as` and guards — built into a text command parser and a JSON event dispatcher.

  • Advanced
  • 22 min
  • 12 questions
  • Lesson 22 of 66

In this lesson you will learn

  • Explain how match/case works: checked top to bottom, the first match wins, capture versus comparison
  • Parse text commands with sequence patterns
  • Check and unpack JSON data with mapping and class patterns
  • Use guards, OR-patterns and as in the right places

A small game bot receives commands such as go north, take lamp key or quit, and an online shop receives JSON events like {"type": "payment", "amount": 16.5}. Checking such data with if/elif gets messy: first you test the length, then the type, then the keys, and then you copy the parts you need into variables. Since Python 3.10 (October 2021) the language has structural pattern matching: match checks the shape of the data and pulls out its parts in one step.

match, case and patternDefinition

match subject: takes the value to examine (the subject), and each case pattern: is a pattern — a description of what the data should look like. Cases are tried from top to bottom; the block of the first matching case runs and the match ends. If none matches, nothing happens.

Literals, OR and the wildcard

The simplest pattern is a literal: case 404: works when the subject == 404. | joins several alternatives, and _ matches anything — it usually comes last as “every other case”. Unlike switch in C or JavaScript, no break is needed, and execution never falls through into the next case.

Python
def http_status(code):
    match code:
        case 200:
            return 'OK'
        case 301 | 302:
            return 'Redirect'
        case 401 | 403:
            return 'No access'
        case 404:
            return 'Not Found'
        case _:
            return f'Unknown code {code}'


for c in (200, 302, 403, 404, 418):
    print(c, http_status(c))
Expected output
200 OK
302 Redirect
403 No access
404 Not Found
418 Unknown code 418
  1. Subject

    The expression after match is evaluated once.

  2. Cases in order

    Patterns are tried from top to bottom: do the shape and the values fit?

  3. Names are bound

    A matching pattern assigns values to its capture names.

  4. Guard

    If there is an if, it must be true; otherwise the next case is tried.

  5. Block

    The block of the first successful case runs and the match ends.

PatternExampleMatches when
literalcase 404: case 'quit':subject == value (None, True, False with is)
capturecase x:always; binds the subject to x
wildcardcase _:always; binds nothing
value (dotted name)case Cmd.QUIT:subject == the constant
ORcase 401 | 403:one of the alternatives matches
sequencecase [x, y, *rest]:a list or tuple of a fitting length
mappingcase {'type': t}:a dict with these keys (other keys are ignored)
classcase Point(x=0):isinstance + the attributes match
AScase [_, _] as pair:the inner pattern matches; binds the whole value
guardcase x if x > 0:the pattern matches and the condition is true

A bare name (case x:) is never a comparison: it is a capture pattern that matches any value and assigns it to that name. So you cannot write a constant as case QUIT: — it does not test the value of QUIT, it overwrites it. To compare with a constant you need a dotted name: Cmd.QUIT, config.LIMIT, Color.RED (an Enum).

Python
QUIT = 'quit'


def handle(command):
    match command:
        case QUIT:                 # a capture pattern, not a comparison!
            return f'quitting... (QUIT is now {QUIT!r})'


class Cmd:
    QUIT = 'quit'
    HELP = 'help'


def handle_fixed(command):
    match command:
        case Cmd.QUIT:             # a dotted name is compared with ==
            return 'bye'
        case Cmd.HELP:
            return 'commands: help, quit'
        case _:
            return f'unknown command {command!r}'


print(handle('hello'))
print(handle_fixed('hello'), '|', handle_fixed('quit'))
Expected output
quitting... (QUIT is now 'hello')
unknown command 'hello' | bye
case QUIT: matched 'hello' too and set the local QUIT to 'hello'. Cmd.QUIT is compared with ==.

Sign up free to keep reading

The rest of the lesson, the quiz and your notes open with an Educora account. Signing up takes a minute, and your progress is saved on all your devices.

Sequence patterns: a command parser

command.split() turns the string into a list of words, and match checks the shape of that list: ['go', direction] — exactly two words, the first is go; ['take', *items] — take and any number of words (they land in the list items); ['quit' | 'exit'] — one word, one of two alternatives. The names inside a pattern capture the matching parts.

Python
DIRECTIONS = {'north', 'south', 'east', 'west'}


def handle(command):
    match command.split():
        case []:
            return 'Say something'
        case ['go', direction] if direction in DIRECTIONS:
            return f'You go {direction}'
        case ['go', _]:
            return 'You cannot go there'
        case ['take']:
            return 'Take what?'
        case ['take', *items]:
            return 'You take ' + ', '.join(items)
        case ['look'] | ['l']:
            return 'A dark room. There is a lamp.'
        case ['quit' | 'exit']:
            return 'Bye!'
        case [verb, *_]:
            return f'I do not know how to {verb!r}'


for line in ['go north', 'go up', 'take lamp key', 'take', 'l', 'exit', 'dance now', '']:
    print(f'{line!r:15} -> {handle(line)}')
Expected output
'go north'      -> You go north
'go up'         -> You cannot go there
'take lamp key' -> You take lamp, key
'take'          -> Take what?
'l'             -> A dark room. There is a lamp.
'exit'          -> Bye!
'dance now'     -> I do not know how to 'dance'
''              -> Say something
For go up the first go pattern matched, but the guard (if direction in DIRECTIONS) was false, so checking went on to the next case. An empty string gives an empty list: case [].

with if/elif

words = command.split()
if len(words) == 2 and words[0] == 'go':
    move(words[1])
elif len(words) >= 2 and words[0] == 'take':
    take(words[1:])
elif words in (['quit'], ['exit']):
    stop()

with match

match command.split():
    case ['go', direction]:
        move(direction)
    case ['take', *items] if items:
        take(items)
    case ['quit' | 'exit']:
        stop()
The same logic: match checks the length and the indices itself and gives the parts names.

A sequence pattern matches lists, tuples, range and other sequences, but not strings, bytes or dictionaries — otherwise every string would be split into letters. A pattern without a star requires an exact length, and *name captures any number of elements as a list (only one star per pattern).

Python
def describe(value):
    match value:
        case []:
            return 'empty sequence'
        case [x]:
            return f'one item: {x}'
        case [x, y]:
            return f'pair: {x}, {y}'
        case [first, *middle, last]:
            return f'from {first} to {last}, {len(middle)} in between'
        case str():
            return f'a string: {value!r}'
        case _:
            return f'something else: {type(value).__name__}'


for v in [[], (7,), [1, 2], range(5), 'ab', {'a': 1}]:
    print(describe(v))
Expected output
empty sequence
one item: 7
pair: 1, 2
from 0 to 4, 3 in between
a string: 'ab'
something else: dict
(7,) is a tuple, yet it matches [x]: square or round brackets make no difference. For range(5), middle became [1, 2, 3].

Worked examples: which case runs?

Problem

1) match (3, 4): → case [x, 0]: print('zero'), case [x, y]: print(x * y)
2) match [1]: → case [x, y, *rest]: print('long'), case _: print('short')
3) match ['take']: → case ['take', *items] if items: print('A'), case ['take', *items]: print(len(items))

Show solutionHide solution

Solution

1) 12: the first pattern needs 0 as the second element (4 ≠ 0); the second gives x = 3, y = 4.
2) short: [x, y, *rest] needs at least 2 elements.
3) 0: the first pattern matches, but the guard is false because items == []; the second case captures items as an empty list.

Mapping patterns: JSON and API responses

A mapping pattern {'key': pattern} requires these keys to exist and their values to match the inner patterns. Unlike sequences, extra keys are ignored — new fields in the JSON do not break the code. If you need the remaining keys, **rest collects them into a separate dictionary. To check a type, put a class pattern right inside: str(city) — “if it is a string, bind it to city”, int() | float() as t — “if it is a number, bind it to t”.

Python
def read_weather(response):
    match response:
        case {'status': 'ok', 'data': {'city': str(city), 'temp': int() | float() as t}}:
            return f'{city}: {t} °C'
        case {'status': 'error', 'message': str(msg)}:
            return 'error: ' + msg
        case {'status': status}:
            return f'unexpected response with status {status!r}'
        case _:
            return 'not a response'


print(read_weather({'status': 'ok', 'data': {'city': 'Baku', 'temp': 23.5}, 'time': '12:00'}))
print(read_weather({'status': 'error', 'message': 'city not found'}))
print(read_weather({'status': 'ok', 'data': {'city': 'Quba', 'temp': 'warm'}}))
print(read_weather(['ok', 23]))
Expected output
Baku: 23.5 °C
error: city not found
unexpected response with status 'ok'
not a response
In the first response the extra key 'time' did not get in the way. In the third, 'temp' is not a number, so the first pattern failed and the response fell to the general {'status': status} pattern. A list never matches mapping patterns.

Class patterns and guards

case Point(x=0, y=y): first checks isinstance(subject, Point) and then the attributes. The positional form Point(0, y) needs __match_args__ (the order of attributes) in the class — @dataclass creates it automatically (see «Type hints and dataclasses»). For built-in types such as int(), str(), float(), list() and dict(), one positional pattern captures the whole value: str(name). After a pattern you can add a guard with if: if the pattern matches but the guard is false, checking moves on to the next case.

Python
from dataclasses import dataclass


@dataclass
class Point:
    x: float
    y: float


@dataclass
class Circle:
    center: Point
    r: float


@dataclass
class Rect:
    corner: Point
    w: float
    h: float


def describe(shape):
    match shape:
        case Circle(Point(0, 0), r):
            return f'circle at the origin, r = {r}'
        case Circle(r=r) if r <= 0:
            return 'invalid circle'
        case Rect(w=w, h=h) if w == h:
            return f'square {w} × {h}'
        case Rect(Point(x, y), w, h):
            return f'rectangle {w} × {h} at ({x}, {y})'
        case _:
            return f'unknown shape: {shape}'


for s in [Circle(Point(0, 0), 5), Circle(Point(2, 3), -1), Rect(Point(1, 1), 4, 4),
          Rect(Point(0, 2), 6, 3), Point(1, 2)]:
    print(describe(s))
print(Rect.__match_args__)
Expected output
circle at the origin, r = 5
invalid circle
square 4 × 4
rectangle 6 × 3 at (0, 2)
unknown shape: Point(x=1, y=2)
('corner', 'w', 'h')
Circle(Point(0, 0), r) is a nested pattern: a circle whose centre is the point (0, 0). Rect(w=w, h=h) if w == h catches a square before the general rectangle, because the special case is written higher up.

Mini project: an event dispatcher

An online shop’s server receives a stream of JSON events. Each event must be routed by its type and shape: log logins, total up orders, drop empty orders, add valid payments to the revenue, reject negative amounts, and report unknown or broken events. All the patterns of the lesson work together here: OR and as, **extra, a nested sequence, type checks and a guard.

Python
import json

raw = '''[
  {"type": "login", "user": "aysel"},
  {"type": "order", "user": "aysel", "items": [{"sku": "pen", "qty": 3, "price": 1.5},
                                               {"sku": "book", "qty": 1, "price": 12.0}]},
  {"type": "order", "user": "murad", "items": []},
  {"type": "payment", "user": "aysel", "amount": 16.5, "currency": "AZN"},
  {"type": "payment", "user": "leyla", "amount": -3, "currency": "AZN"},
  {"type": "logout", "user": "aysel", "reason": "timeout"},
  {"type": "upload", "file": "cv.pdf"},
  "garbage"
]'''

revenue = 0
for event in json.loads(raw):
    match event:
        case {'type': 'login' | 'logout' as kind, 'user': str(user), **extra}:
            print(f'{user}: {kind}' + (f' {extra}' if extra else ''))
        case {'type': 'order', 'user': user, 'items': [_, *_] as items}:
            total = sum(item['qty'] * item['price'] for item in items)
            print(f'{user}: order of {len(items)} items, {total:.2f} AZN')
        case {'type': 'order', 'user': user}:
            print(f'{user}: empty order ignored')
        case {'type': 'payment', 'amount': int() | float() as amount, 'currency': 'AZN'} if amount > 0:
            revenue += amount
        case {'type': 'payment', 'user': user, 'amount': amount}:
            print(f'{user}: rejected payment {amount}')
        case {'type': str(kind)}:
            print(f'unknown event type {kind!r}')
        case _:
            print(f'not an event: {event!r}')
print('revenue:', revenue, 'AZN')
Expected output
aysel: login
aysel: order of 2 items, 16.50 AZN
murad: empty order ignored
leyla: rejected payment -3
aysel: logout {'reason': 'timeout'}
unknown event type 'upload'
not an event: 'garbage'
revenue: 16.5 AZN
[_, *_] as items means “a list with at least one element”, so an empty order falls to the next case. A payment is added to the revenue only when the guard holds; a negative amount is rejected by the next, more general payment pattern.

Exercise

Complete classify(value): bool → 'bool' (already written; it must come first because True is also an int), 0 → 'zero', a positive integer → 'positive int', a negative integer → 'negative int', a float → 'float', the empty string → 'empty string', any other string → 'string', a sequence of two elements → 'pair', everything else → 'other'.

Exercise · Python
def classify(value):
    match value:
        case bool():
            return 'bool'
        # add the other cases here
        case _:
            return 'other'


for v in [0, 42, -7, 3.14, '', 'hi', (1, 2), [1, 2, 3], True, None]:
    print(repr(v), '->', classify(v))
Expected output
0 -> zero
42 -> positive int
-7 -> negative int
3.14 -> float
'' -> empty string
'hi' -> string
(1, 2) -> pair
[1, 2, 3] -> other
True -> bool
None -> other

Exercise

Finish the command calculator with sequence patterns: add a b, mul a b, neg a and sum a b c … with at least one number. Convert the numbers to float; anything else must return 'error'.

Exercise · Python
def calc(line):
    match line.split():
        case ['add', a, b]:
            return float(a) + float(b)
        # add: mul a b, neg a, sum a b c ... (at least one number)
        case _:
            return 'error'


for line in ['add 2 3', 'mul 4 2.5', 'neg 7', 'sum 1 2 3 4', 'sum', 'add 1']:
    print(line, '=', calc(line))
Expected output
add 2 3 = 5.0
mul 4 2.5 = 10.0
neg 7 = -7.0
sum 1 2 3 4 = 10.0
sum = error
add 1 = error

Remember

  • match tries cases from top to bottom; the first match runs, no break is needed and nothing falls through.
  • A bare name is a capture pattern that matches anything; write constants as dotted names (Cmd.QUIT).
  • Sequence patterns match lists and tuples (not strings); *rest captures the remaining elements.
  • Mapping patterns ignore extra keys; **rest collects the others; str(x) and int() | float() as n check types.
  • Class patterns check isinstance and attributes (__match_args__ comes free with a dataclass); an if guard is checked after the pattern.
Spotted a mistake or something inaccurate in this lesson?

Check yourself

12 questions. Every correct answer earns XP.

Question 1 / 12

Question 1 / 12. Since which Python version is match/case available?