Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Python  Module 3 – Control flow: decisions, loops and pattern matching

Structural matching: lists, dicts and classes

Match lists, tuples, dictionaries and objects by their shape in Python, capture their parts with sequence, mapping, class and as patterns, and handle JSON data.

  • Intermediate
  • 20 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Match sequences and mappings and capture their parts in one pattern
  • Match class instances with positional and keyword patterns
  • Check the type of a value inside a pattern with int(), str() and bool()
  • Predict which case of a structural match runs for a given subject
  • Handle JSON-like data, such as parsed events, with match

Before you start

What you’ll learn · Before you start

What you will learn

  • Match sequences and mappings and capture their parts in one pattern
  • Match class instances with positional and keyword patterns
  • Check the type of a value inside a pattern with int(), str() and bool()
  • Predict which case of a structural match runs for a given subject
  • Handle JSON-like data, such as parsed events, with match

Before you start

On this page

The patterns of the last lesson compared a whole value: is it 404, is it "play". Patterns can also describe the shape of a value: a list of two words that starts with "done", a dictionary with a "host" key, a rectangle whose width equals its height. When a pattern like that fits, the parts it names are captured in the same step, so the case block can use them straight away. Python calls this structural pattern matching: Testing a value by its shape, such as a list of two items or a dict with a "host" key, and capturing its parts in the same step, as a match statement does with sequence, mapping and class patterns..

The three structural kinds of pattern, for sequences, mappings and objects, come one at a time, each with a figure that steps one real subject: The value written after match. Python evaluates it once, then tries the patterns of the cases against it, from the top. More in “Pattern matching with match and case” through the cases. Then they are combined to tell apart eight events that arrive as JSON, the malformed ones included, which is where the checks of types and the order of the cases decide everything.

A sequence pattern checks the length, then each item

A pattern written like a list, [a, b], is a sequence pattern: A pattern written like a list or a tuple, such as [first, *rest]. It fits a sequence of the right length, but never a str, bytes or bytearray, and matches each item against the pattern in its place.. It fits a sequence with exactly that many items and matches each item against the pattern in its place. A starred name, *rest, takes any number of items. The words a user types after a program’s name are a list of strings, which makes a to-do program’s command line a good fit:

A command line matched by its shape Python · todo_args.py
def todo(args):
    """Answer the command line of a small to-do program: the words typed after its name."""
    match args:
        case [] | ["help"]:
            return "usage: todo list | todo add TEXT | todo done NUMBER"
        case ["list"]:
            return "showing every task"
        case ["add"]:
            return "add needs the text of the task"
        case ["add", *words]:
            return "added: " + " ".join(words)
        case ["done", number] if number.isdecimal():
            return f"task {number} is done"
        case [command, *rest]:
            return f"not understood: {command} followed by {rest}"
        case _:
            return f"expected a list of words, got {args!r}"


# A real program would call todo(sys.argv[1:]); these are argument lists it could get.
for args in [[], ["list"], ["add", "buy", "milk"], ["add"], ["done", "3"], ["done", "x"], ["remove", "2"], "list"]:
    print(repr(args), "->", todo(args))

Output

[] -> usage: todo list | todo add TEXT | todo done NUMBER
['list'] -> showing every task
['add', 'buy', 'milk'] -> added: buy milk
['add'] -> add needs the text of the task
['done', '3'] -> task 3 is done
['done', 'x'] -> not understood: done followed by ['x']
['remove', '2'] -> not understood: remove followed by ['2']
'list' -> expected a list of words, got 'list'

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 todo_args.py

Read the cases from the top:

  • [] fits only an empty list (or tuple), and ["list"] only a list holding exactly the one word "list".
  • ["add", *words] fits a list that starts with "add", however long it is; words gets the remaining items as a list. That list may be empty, which is why ["add"] on its own is caught by the case above it.
  • ["done", number] if number.isdecimal() combines a sequence pattern with a guard: An if condition after a case's pattern, as in case code if code < 200:. Python checks it only once the pattern fits; when it is false, the next case is tried. More in “Pattern matching with match and case”, which checks the captured part.
  • [command, *rest] fits any list with at least one item. *_ would accept the same items without keeping them.

Follow one subject through those cases, the words of todo add buy milk. Watch which test each case fails on:

Interactive · stage by stage todo(["add", "buy", "milk"]), case by case Step through the cases in the order Python tries them. Each box says what its sequence pattern found.
todo(["add", "buy", "milk"]), case by case, step 6 of 6. Showing match args:, case [] | ["help"]: (no: 3 items, not 0 or 1), case ["list"]: (no: needs exactly 1 item), case ["add"]: (no: needs exactly 1 item), case ["add", *words]: (runs: added: buy milk), case ["done", number]: (never tried), case [command, *rest]: (never tried), case _: (never tried). In focus: case ["done", number]:, case [command, *rest]:, case _:.match args:['add', 'buy', 'milk']case [] | ["help"]:no: 3 items, not 0 or 1case ["list"]:no: needs exactly 1 itemcase ["add"]:no: needs exactly 1 itemcase ["add", *words]:runs: added: buy milkcase ["done", number]:never triedcase [command, *rest]:never triedcase _:never tried

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. The subject. The program calls todo(["add", "buy", "milk"]), the words typed after the program's name. Python evaluates the subject, args, once: a list of three strings.
  2. Two lengths that do not fit. [] fits only a sequence with no items, and ["help"] only one with exactly one. The subject has three, so neither alternative fits, and no item is compared at all.
  3. Exactly one item. ["list"] and ["add"] are fixed-length patterns of one item each. The length test fails before Python looks at "add", so both cases fail.
  4. A starred name fits. With *words the pattern needs at least one item, and three is enough. The first item must equal "add", and it does; words takes the remaining items as a list.
  5. Its block runs. The block returns "added: " + " ".join(words), which is "added: buy milk". That ends the match statement.
  6. The rest is never tried. The last three cases are never tried for this subject. Only a subject that every case above misses gets to case _, such as the string "list": sequence patterns never match a str.

Three cases failed on the length alone, before a single word was compared, and the starred pattern fitted because it asks for at least one item rather than an exact number.

The last line passes a string, "list", instead of a list of words, and it reaches the final case _. A string is a sequence of characters in most of Python, but sequence patterns never match strings, bytes or bytearrays, so a string cannot be split into letters by accident. Square brackets and round ones mean the same in a pattern: (x, y) also fits a list, and [x, y] also fits a tuple (one item in round brackets needs a comma, (x,); without it the brackets only group). A sequence pattern can hold one starred name at most, in any position, as in [*rest, last].

Checkpoint

Check: Sequence patterns

  1. Question 1 of 2 What does todo(["done", "x"]) from todo_args.py return?

    Choose one answer.

    A hint

    The pattern fits first; then its guard decides.

    Show the answer: Question 1 of 2

    Answer: not understood: done followed by ['x']

    The subject has two items, so ["done", number] fits and binds number to "x". Its guard is False, so the case is not chosen; the next case, [command, *rest], fits and returns "not understood: done followed by ['x']", as the program printed.

  2. Question 2 of 2 Why does todo("list"), with a string instead of a list, reach the final case _?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Sequence patterns never match a str, bytes or bytearray

    Sequence patterns refuse str, bytes and bytearray, so a string cannot be split into letters by accident. Every case of todo() is a sequence pattern except the last, so the string "list" reaches case _.

A mapping pattern needs only the keys it names

A pattern written like a dictionary, with fixed keys such as "host", is a mapping pattern: A pattern written like a dict, such as {"host": host}. It fits a mapping that has at least the keys it names and ignores the others; **rest collects them, and {} fits every mapping.. It fits a dictionary that has at least those keys, and matches each key’s value against the pattern after its colon. This function finds the server address in a program’s settings, and uses port 443, the default port of https addresses, when none is given:

Settings matched by the keys they have Python · settings.py
def address(settings):
    match settings:
        case {"host": host, "port": port}:
            return f"{host}:{port}"
        case {"host": host}:
            return f"{host}:443"
        case {}:
            return "no host in these settings"
        case _:
            return "the settings are not a dictionary"


for settings in [
    {"host": "example.org", "port": 8080},
    {"host": "example.org", "timeout": 5},
    {"port": 8080},
    {},
    ["example.org", 8080],
]:
    print(settings, "->", address(settings))

Output

{'host': 'example.org', 'port': 8080} -> example.org:8080
{'host': 'example.org', 'timeout': 5} -> example.org:443
{'port': 8080} -> no host in these settings
{} -> no host in these settings
['example.org', 8080] -> the settings are not a dictionary

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 settings.py

The second dictionary has an extra key, "timeout", and still fits {"host": host}: keys that a mapping pattern does not mention are ignored. That is usually what you want for data from outside, which often carries fields your code does not need, but it has a surprising consequence. Step through the third settings, {"port": 8080}, which has no "host" at all, and see which case answers:

Interactive · stage by stage address({"port": 8080}), case by case Step through the cases in order. Each box says which keys its mapping pattern needs and what it found.
address({"port": 8080}), case by case, step 6 of 6. Showing match settings:, keys "host" and "port" (no "host" key: no fit), key "host" (no "host" key: no fit), no keys named (runs: no host in these), anything else (never tried). In focus: anything else.match settings:{"port": 8080}keys "host" and "port"no "host" key: no fitkey "host"no "host" key: no fitno keys namedruns: no host in theseanything elsenever tried

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. The subject. address({"port": 8080}) reaches the match. The subject is a dictionary with one key, "port", and no "host".
  2. A key is missing. The first pattern needs both "host" and "port". The subject is a mapping and has "port", but "host" is missing, so the pattern fails.
  3. Missing again. {"host": host} asks for one key only, and it is the one the subject lacks, so this case fails too.
  4. {} fits. {} names no keys, so a dictionary has every key it asks for, whatever it holds. The pattern fits {"port": 8080}, and every other dictionary as well.
  5. Its block runs. The block returns "no host in these settings". The case was meant for an empty dictionary, and it also answers for this one.
  6. Never tried. case _ is never tried for a dictionary: {} has caught every one. Only a subject that is not a mapping, such as the list in the last line of settings.py, gets that far.

The case meant for empty settings answered for a dictionary that holds a key.

Using case {}: to catch an empty dictionary

The pattern {} names no keys, so it fits every dictionary, as {"port": 8080} shows. To catch only an empty one, add a guard: case {} if not settings:.

To keep the keys a pattern did not name, end it with **rest: {"host": host, **rest} puts every other key and its value into a new dictionary called rest. A list is not a mapping, so the last settings reach case _.

Checkpoint

Check: Mapping patterns

  1. Question 1 of 2 What does address() from settings.py return for {"host": "example.org", "timeout": 5, "port": 80}?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: example.org:80

    A mapping pattern needs at least the keys it names. {"host": host, "port": port} finds both, binds host and port, and the extra "timeout" changes nothing, so the function returns "example.org:80".

  2. Question 2 of 2 Which case runs only when the subject settings is an empty dictionary?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: case {} if not settings:

    A mapping pattern tests for the keys it names and nothing else, so no pattern alone can ask for "no keys". Write case {} if not settings:, or test the length in a guard.

A class pattern checks the class, then the attributes

A pattern that looks like a call, Circle(radius=r), is a class pattern: A pattern written like a call, such as Circle(radius=r). It fits an instance of the class, tested with isinstance(), whose attributes match the patterns given for them.. It fits an object of that class (the check is isinstance(), so subclasses fit too) and matches its attributes against the patterns given for them. The keyword form, attribute=pattern, works with any class. The positional form, Rectangle(w, h), needs to know which attribute each position means, and a data class (made with @dataclass) tells it by setting __match_args__: A class attribute holding a tuple of attribute names. It tells a class pattern which attribute each positional sub-pattern stands for; @dataclass sets it to the fields in the order they are declared. to its fields in order:

Shapes matched by class and attributes Python · shapes.py
import math
from dataclasses import dataclass


@dataclass
class Circle:
    radius: float


@dataclass
class Rectangle:
    width: float
    height: float


@dataclass
class Triangle:
    base: float
    height: float


def describe(shape):
    match shape:
        case Circle(radius=r):
            return f"circle, area {math.pi * r * r:.2f}"
        case Rectangle(w, h) if w == h:
            return f"square, area {w * h}"
        case Rectangle(w, h):
            return f"rectangle, area {w * h}"
        case Triangle(base=b, height=h):
            return f"triangle, area {b * h / 2}"
        case _:
            return f"not a shape: {shape!r}"


print("Rectangle.__match_args__ is", Rectangle.__match_args__)
for shape in [Circle(1.5), Rectangle(3, 4), Rectangle(2, 2), Triangle(6, 2), (3, 4)]:
    print(shape, "->", describe(shape))

Output

Rectangle.__match_args__ is ('width', 'height')
Circle(radius=1.5) -> circle, area 7.07
Rectangle(width=3, height=4) -> rectangle, area 12
Rectangle(width=2, height=2) -> square, area 4
Triangle(base=6, height=2) -> triangle, area 6.0
(3, 4) -> not a shape: (3, 4)

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 shapes.py

Rectangle(w, h) means Rectangle(width=w, height=h), because Rectangle.__match_args__ is ('width', 'height'). The guard if w == h picks out squares before the general rectangle case. The tuple (3, 4) holds the same numbers as a rectangle, but it is not a Rectangle object, so it fits none of the class patterns. Step through the checks for one shape, the square Rectangle(2, 2):

Interactive · stage by stage describe(Rectangle(2, 2)), check by check Step through the checks Python makes for the class patterns of shapes.py. Each box says what the check found.
describe(Rectangle(2, 2)), check by check, step 8 of 8. Showing match shape:, case Circle(radius=r): (no: not a Circle), case Rectangle(w, h) (yes: it is a Rectangle), positions to attributes (w, h mean width, height), width, matched by w (w is 2), height, matched by h (h is 2), the guard (True: 2 == 2), the block (runs: 'square, area 4'). In focus: the block.match shape:Rectangle(width=2, height=2)case Circle(radius=r):no: not a Circlecase Rectangle(w, h)yes: it is a Rectanglepositions to attributesw, h mean width, heightwidth, matched by ww is 2height, matched by hh is 2the guardTrue: 2 == 2the blockruns: 'square, area 4'

The drawing shows the whole scene; its 8 steps are listed below.

Every step as text
  1. The subject. The loop calls describe(Rectangle(2, 2)). The data class prints itself as Rectangle(width=2, height=2): one object with two attributes.
  2. Not a Circle. A class pattern first tests the class with isinstance(). The subject is not a Circle, so Circle(radius=r) fails at once and its radius is never read.
  3. The class fits. isinstance(shape, Rectangle) is True, so the next pattern goes on to its sub-patterns. An object of a subclass of Rectangle would pass this test too.
  4. Positions become names. Rectangle(w, h) has two positional sub-patterns. Python reads Rectangle.__match_args__, which @dataclass set to ('width', 'height'), so the pattern means Rectangle(width=w, height=h).
  5. The width. Python reads the attribute shape.width, which is 2, and matches it against the capture pattern w. A capture fits any value, so w is now 2.
  6. The height. shape.height is 2 as well, so h is 2. Every sub-pattern has fitted, so the class pattern fits as a whole.
  7. The guard decides. Only now is the guard evaluated. 2 == 2 is True, so this case is chosen. For Rectangle(3, 4) the guard would be False, and the next case, Rectangle(w, h) without a guard, would answer.
  8. Its block runs. The block returns "square, area 4", the line the program printed for this shape. The cases below it are never tried.

The class came first, then the names from __match_args__, then one attribute per sub-pattern, and the guard last. An attribute that the object does not have makes the pattern fail, not raise an error, so the next case is tried.

A class you write yourself has no __match_args__ unless you set it, so positional patterns fail with an error that says how many positions it accepts:

A positional pattern without __match_args__ Python · plain_class.py
class Version:
    def __init__(self, major, minor):
        self.major = major
        self.minor = minor


version = Version(3, 14)

match version:
    case Version(major=3, minor=minor):
        print(f"keyword pattern: Python 3.{minor}")

match version:
    case Version(3, minor):
        print(f"positional pattern: Python 3.{minor}")

Output (exit status 1)

keyword pattern: Python 3.14

Printed as an error (standard error)

Traceback (most recent call last):
  File "plain_class.py", line 14, in <module>
    case Version(3, minor):
         ~~~~~~~^^^^^^^^^^
TypeError: Version() accepts 0 positional sub-patterns (2 given)

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 plain_class.py

Write the keyword form, make the class a data class, or give it the attribute yourself: __match_args__ = ("major", "minor") in the class body.

Remember the brackets

A class pattern needs its parentheses even when it captures nothing: case Circle():. Written as case Circle:, it is a bare name, a capture pattern: A bare name in a case, such as case code:, which fits any subject and binds it to that name. It never compares, so case SHIPPED: overwrites a constant instead of testing it. More in “Pattern matching with match and case” that fits everything and rebinds the name Circle, the trap of the previous lesson.

Checkpoint

Check: Class patterns and __match_args__

  1. Question 1 of 2 A data class Size declares its fields as height: int, then width: int. What does case Size(a, b): bind for Size(height=3, width=4)?

    Choose one answer.

    A hint

    @dataclass sets __match_args__ from the fields, in the order the class lists them.

    Show the answer: Question 1 of 2

    Answer: a is 3 and b is 4, because height is the first field

    Positional sub-patterns are turned into keyword ones with __match_args__. @dataclass sets it to the field names in the order they are declared, here ('height', 'width'), so a gets the height, 3, and b the width, 4.

  2. Question 2 of 2 Why does the tuple (3, 4) fit none of the class patterns in shapes.py?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It is not an instance of Circle, Rectangle or Triangle

    Holding the same numbers is not enough: a class pattern checks the class with isinstance() before anything else. (3, 4) is a tuple, so it falls through to case _ and the program prints "not a shape: (3, 4)".

Patterns for built-in types check the type of the whole value

For a handful of built-in types (bool, bytearray, bytes, dict, float, frozenset, int, list, set, str and tuple), a class pattern with one positional pattern matches the whole value. int(n) fits any integer and captures it as n; str(name) fits any string. That is the way to check the type of a value inside a pattern, before any guard compares it. One surprise: bool is a subclass of int, so int(n) also fits True and False. Where that matters, put a case for bool() above it.

JSON makes that surprise real, because its true and false become True and False. This program reads the same key four times, as a number, as true, as text and as a number with a decimal point, once without a case for bool() and once with one above int(x):

int(x) checks the type, and lets True in Python · type_patterns.py
import json


def x_of(event):
    match event:
        case {"x": int(x)}:
            return f"x is {x}"
        case _:
            return "no whole-number x"


def x_of_checked(event):
    match event:
        case {"x": bool()}:
            return "x is true or false"
        case {"x": int(x)}:
            return f"x is {x}"
        case _:
            return "no whole-number x"


# The same key four times, as JSON: a number, true, text and a number with a decimal point.
for line in ['{"x": 120}', '{"x": true}', '{"x": "120"}', '{"x": 120.0}']:
    event = json.loads(line)
    print(f"{line:<13} {x_of(event):<18} {x_of_checked(event)}")

Output

{"x": 120}    x is 120           x is 120
{"x": true}   x is True          x is true or false
{"x": "120"}  no whole-number x  no whole-number x
{"x": 120.0}  no whole-number x  no whole-number x

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 type_patterns.py

In the middle column, x_of() takes true for a whole number and prints x is True; in the last column, x_of_checked() catches it first. The text "120" and the float 120.0 fit int(x) in neither, because a pattern checks the type and never converts anything. Press Edit, move the bool() case of x_of_checked() below the int(x) case and run it again: the last column then says x is True as well.

Version note

Python 3.15 adds frozendict to the list of built-in types that match the whole value, together with the new built-in type itself. This track runs Python 3.14.

Checkpoint

Check: Type checks with int() and str()

  1. Question 1 of 2 describe() from events.py receives {"type": "scroll", "dy": true}, parsed from JSON. What does it return?

    Choose one answer.

    A hint

    json.loads() turns true into True. Which class is True an instance of?

    Show the answer: Question 1 of 2

    Answer: scroll down True lines

    int(dy) checks the type with isinstance(), and True is an instance of int. The scroll-up guard is False, so the scroll-down case returns "scroll down True lines". A case for bool() above the int cases keeps true and false out.

  2. Question 2 of 2 What does case str(name): bind for the subject "Mei"?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: name is "Mei", the whole string

    A class pattern for one of the listed built-in types, with one positional pattern, matches the whole subject: the subject must be a str, and name captures all of it.

Patterns nest, and as keeps a part you checked

Patterns nest inside one another to any depth, the way the data does: a sequence pattern can hold class patterns, a mapping pattern can hold sequence patterns. The resize events of the next section are a dictionary that holds a list of two numbers, and one nested pattern takes such an event apart: {"type": "resize", "size": [int(width), int(height)]}. The tree shows its parts at once:

A tree of patterns: a mapping pattern checks the type and size keys; the size list must hold two ints, captured as width and height.Mapping pattern:a dict with the keys"type" and "size"?"type": "resize"literal: thevalue mustequal it"size": [ … , … ]sequence:exactly twoitemsint(width)an int,capturedas widthint(height)an int,capturedas height"resize"[1280, 720]1280720

How {"type": "resize", "size": [int(width), int(height)]} takes an event apart

Text description of the diagram

The diagram is a tree that runs from top to bottom, with the values of the event {"type": "resize", "size": [1280, 720]} on its arrows.

  • At the top is the mapping pattern. It fits only a dictionary (or another mapping) that has both keys, "type" and "size"; any other keys are ignored.
  • One branch below it checks the value of "type": the text "resize" must equal the literal pattern "resize".
  • The other branch checks the value of "size": the list [1280, 720] must fit the sequence pattern, a sequence of exactly two items.
  • Below the sequence pattern are two class patterns. int(width) fits the first item, 1280, only if it is an int, and captures it as width; int(height) does the same for the second item, capturing 720 as height.
  • Only when every part fits does the case run, with width and height set.

Now step through the same pattern against {"type": "resize", "size": [1280, 720]}, one part at a time. Each value travels down its arrow to the pattern that checks it:

Interactive · step by step One nested pattern takes a resize event apart Step through the checks. A part appears when its pattern is tried, and the value it is given travels down its arrow.
One nested pattern takes a resize event apart, step 6 of 6. Showing mapping pattern (every part fits), "type": "resize" (equal: it fits), "size": [ … , … ] (2 items: it fits), int(width) (width = 1280), int(height) (height = 720). In focus: mapping pattern.mapping patternevery part fits"type": "resize"equal: it fits"size": [ … , … ]2 items: it fitsint(width)width = 1280int(height)height = 720

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. A mapping first. The subject is the fifth event of events.py once json.loads() has read it: {"type": "resize", "size": [1280, 720]}. The outer pattern needs a mapping with the keys "type" and "size", and this dict has both.
  2. The type is a literal. The value of "type" goes to the literal pattern "resize". The two strings are equal, so this part fits.
  3. The size is a sequence. The value of "size", the list [1280, 720], goes to a sequence pattern of two items. A list is a sequence, and it holds exactly two items, so its items are matched one by one, from the left.
  4. The first item. int(width) gets 1280. A class pattern for int with one positional pattern matches the whole value: 1280 is an int, so it fits, and the capture keeps it as width.
  5. The second item. int(height) gets 720, also an int, so height is 720. Had the second item been the text "720", int(height) would not fit it, and the whole case would fail.
  6. Every part fits. Every sub-pattern has fitted, so the whole case does, with width and height set: its block returns "window is now 1280 x 720".

Each part checked one thing, and only when all five had fitted did the case run with width and height set. A wrong type or a wrong length at any depth fails the whole case.

To capture a part that you have also described with a pattern, add as and a name after it, an as pattern: A pattern followed by as and a plain name, such as ("Enter" | "Tab") as key. When the pattern fits, the name is bound to the value it matched.: ("Enter" | "Tab") as key checks that the key is one of two strings and keeps the one it was. The name after as must be a plain name; other targets, such as a tuple of names, are a SyntaxError:

as needs a single name Python · as_target.py
match [3, 4]:
    case [x, y] as (width, height):
        print(width, height)

Output (exit status 1)

Printed as an error (standard error)

  File "as_target.py", line 2
    case [x, y] as (width, height):
                   ^^^^^^^^^^^^^^^
SyntaxError: cannot use tuple as pattern target

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 as_target.py

Version note

The error message above, “cannot use tuple as pattern target”, comes from Python 3.14, which improved the messages for wrong targets after as in imports, except clauses and patterns. Python 3.15 also accepts a unary plus in literal patterns, as in case +1:, to match the unary minus that was always allowed; Python 3.14, which this track runs, rejects it with a SyntaxError.

Checkpoint

Check: Nested patterns and as

  1. Question 1 of 2 Which of these events does the pattern {"type": "resize", "size": [int(width), int(height)]} fit?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: {"type": "resize", "size": [800, 600], "dpr": 2}

    Every part of a nested pattern must fit: the dict needs both keys, "type" must equal "resize", "size" must be a sequence of two items, and each item must be an int. Keys the pattern does not name are ignored.

  2. Question 2 of 2 Which of these as patterns does Python accept?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: case [x, y] as point:

    as must be followed by one plain name other than _. When the pattern before as fits, that name is bound to the value the pattern matched.

JSON events: the specific shapes first, a catch-all last

A web page can send what the user did to a server as small JSON objects. json.loads() turns each one into Python values: a JSON object becomes a dict, an array a list, true becomes True, and numbers become int or float. Data like that is exactly what structural patterns are for:

Telling events from JSON apart Python · events.py
import json

# Events as a web page might send them to a server, one JSON value per line.
messages = """
{"type": "click", "x": 120, "y": 45, "button": "left"}
{"type": "key", "key": "Enter"}
{"type": "key", "key": "s", "ctrl": true}
{"type": "scroll", "dy": -3}
{"type": "resize", "size": [1280, 720]}
{"type": "click", "x": "120"}
{"type": "zoom", "level": 2}
["click", 120, 45]
"""


def describe(event):
    match event:
        case {"type": "click", "x": int(x), "y": int(y)}:
            return f"click at ({x}, {y})"
        case {"type": "key", "key": str(key), "ctrl": True}:
            return f"shortcut Ctrl+{key.upper()}"
        case {"type": "key", "key": ("Enter" | "Tab") as key}:
            return f"{key} key"
        case {"type": "scroll", "dy": int(dy)} if dy < 0:
            return f"scroll up {-dy} lines"
        case {"type": "scroll", "dy": int(dy)}:
            return f"scroll down {dy} lines"
        case {"type": "resize", "size": [int(width), int(height)]}:
            return f"window is now {width} x {height}"
        case {"type": str(kind), **rest}:
            return f"cannot handle a {kind!r} event with {rest}"
        case _:
            return f"not an event: {event!r}"


for line in messages.strip().splitlines():
    print(describe(json.loads(line)))

Output

click at (120, 45)
Enter key
shortcut Ctrl+S
scroll up 3 lines
window is now 1280 x 720
cannot handle a 'click' event with {'x': '120'}
cannot handle a 'zoom' event with {'level': 2}
not an event: ['click', 120, 45]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 events.py

Each case states the shape of one kind of event, and each line of output shows a rule at work:

  • The first click has a "button" key that no pattern mentions; it is ignored.
  • "ctrl": True is a literal pattern, compared by identity, so it fits JSON’s true and nothing else.
  • int(x) and int(y) check the types as well as capturing, so the click whose "x" is the text "120" and has no "y" fits no click case.
  • {"type": str(kind), **rest} catches every event with a text type that no case above it fitted, the click with the wrong "x" as well as the zoom, and reports what else it carried.
  • The JSON array at the end is a list, not a dictionary, so only case _ fits it.

Follow the malformed click through the eight cases. Watch where it is caught, and what **rest keeps:

Interactive · stage by stage A malformed click through the event cases Step through the cases of describe() for {"type": "click", "x": "120"}. Each box says what its pattern found.
A malformed click through the event cases, step 6 of 6. Showing match event:, click (no: x is text, no "y"), key with Ctrl (no: "type" is not theirs), Enter or Tab key (no: "type" is not theirs), scroll up (no: "type" is not theirs), scroll down (no: "type" is not theirs), resize (no: "type" is not theirs), any event typed by a str (runs: cannot handle it), case _ (never tried). In focus: case _.match event:{"type": "click", "x": "120"}clickno: x is text, no "y"key with Ctrlno: "type" is not theirsEnter or Tab keyno: "type" is not theirsscroll upno: "type" is not theirsscroll downno: "type" is not theirsresizeno: "type" is not theirsany event typed by a strruns: cannot handle itcase _never tried

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. The subject. The sixth line of events.py is {"type": "click", "x": "120"}. json.loads() makes it a dict whose "x" is the string "120", and it has no "y" at all.
  2. Not a valid click. The click case has the right "type", but it needs "x" to be an int and a "y" key as well. "x" is text, which int(x) does not fit, and "y" is missing: either is enough for the case to fail.
  3. Five other types. The next five cases need "type" to be "key", "scroll" or "resize", and keys this event does not have. The subject's "type" is "click", so all five fail.
  4. The general case fits. This pattern needs only a "type" key whose value is a str, and "click" is one, so kind is 'click'. **rest collects every key the pattern did not name: rest is {'x': '120'}.
  5. The event is reported. The block returns "cannot handle a 'click' event with {'x': '120'}", the sixth line of the output. The malformed click is reported instead of passing as a click at some position.
  6. Never tried. case _ is never tried for this event. Only a value that is not a dict with a string "type", such as the JSON array on the last line, gets that far.

The click case refused it, the five cases for other types failed on their "type", and the general case reported it, with **rest holding the one key it did not name, "x".

Order matters here as much as with literals: the cases for a particular kind of event come first, and the general ones last. When nothing fits, the final cases say so instead of letting a malformed event pass as a correct one.

Key idea

Write one case per shape of data you expect, the most specific first, and end with cases that catch and report whatever fits none of them.

Checkpoint

Check: JSON data, specific shapes first

  1. Question 1 of 2 What does describe() from events.py return for {"type": "click", "x": 5}?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: cannot handle a 'click' event with {'x': 5}

    {"type": "click", "x": int(x), "y": int(y)} needs every key it names, and "y" is missing. The case {"type": str(kind), **rest} then fits, with kind 'click' and rest {'x': 5}, and the event is reported.

  2. Question 2 of 2 A new kind of event arrives: {"type": "tap", "x": 1, "y": 2}. What does describe() return?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: cannot handle a 'tap' event with {'x': 1, 'y': 2}

    The specific cases describe the events the program knows; the general case catches any other typed event and says what arrived. A new kind of event is reported, not handled by mistake as another kind.

JSON Viewer & Tree Editor Explore a JSON document as a tree to see which keys and nesting your patterns need to describe. Python Online Compiler Run events.py with events of your own, such as a key event without a key.

Practise: summarise chat messages

The exercise brings the patterns of this lesson together on one kind of data. A chat app receives six kinds of message as JSON, and summarise() must describe each one in a line, with mapping patterns for the keys, class patterns such as str(name) and int(number) for the types, a nested sequence pattern for an image’s size and guards for the values. Its sample tests also send malformed messages, which must come out as unknown message.

Exercise · Medium · Python

Summarise chat messages with structural patterns

A chat app receives its messages as JSON, and json.loads() turns each one into a dictionary. Write summarise(message), which returns a one-line summary of a message, using a match statement (the tests check that there is one).

These are the six kinds of message. Names, texts, reasons and emoji are strings; a message number is a whole number.

  • {"type": "text", "from": "Asha", "text": "Hello"} gives Asha: Hello
  • {"type": "image", "from": "Ravi", "size": [640, 480]} gives Ravi sent a 640x480 image; the size is a list of exactly two whole numbers, both greater than 0
  • {"type": "join", "user": "Mei"} gives Mei joined
  • {"type": "leave", "user": "Mei", "reason": "timeout"} gives Mei left (timeout)
  • {"type": "leave", "user": "Mei"}, without a reason, gives Mei left
  • {"type": "reaction", "from": "Asha", "emoji": "👍", "to": 42} gives Asha reacted 👍 to message 42

A message may carry other keys too, such as "id" or "pinned": ignore them. Anything else gives unknown message: a missing key, a value of the wrong type ("to": "42" is text, not a number), a size that is not two whole numbers greater than 0, a type the app does not know, or something that is not a dictionary at all.

Starter code · chat.py

def summarise(message):
    """Return a one-line summary of a chat message, or "unknown message"."""
    match message:
        case {"type": "join", "user": str(name)}:
            return f"{name} joined"
        case _:
            return "unknown message"
The sample tests · test_chat.py
import ast
from pathlib import Path

from chat import summarise


def test_text():
    """summarises a text message"""
    assert summarise({"type": "text", "from": "Asha", "text": "Hello"}) == "Asha: Hello"


def test_image():
    """summarises an image with its size"""
    assert summarise({"type": "image", "from": "Ravi", "size": [640, 480]}) == "Ravi sent a 640x480 image"


def test_join_and_leave():
    """summarises people joining and leaving, with or without a reason"""
    assert summarise({"type": "join", "user": "Mei"}) == "Mei joined"
    assert summarise({"type": "leave", "user": "Mei", "reason": "timeout"}) == "Mei left (timeout)"
    assert summarise({"type": "leave", "user": "Mei"}) == "Mei left"


def test_reaction():
    """summarises a reaction to a message"""
    assert summarise({"type": "reaction", "from": "Asha", "emoji": "👍", "to": 42}) == "Asha reacted 👍 to message 42"


def test_extra_keys():
    """ignores keys it does not need"""
    assert summarise({"type": "text", "from": "Asha", "text": "Hi", "id": 7, "pinned": False}) == "Asha: Hi"
    assert summarise({"id": 8, "user": "Mei", "type": "join"}) == "Mei joined"


def test_malformed():
    """treats messages with missing keys or values of the wrong type as unknown"""
    assert summarise({"type": "text", "from": "Asha"}) == "unknown message"
    assert summarise({"type": "text", "from": 5, "text": "Hello"}) == "unknown message"
    assert summarise({"type": "image", "from": "Ravi", "size": [640]}) == "unknown message"
    assert summarise({"type": "image", "from": "Ravi", "size": [640, 0]}) == "unknown message"
    assert summarise({"type": "image", "from": "Ravi", "size": ["640", "480"]}) == "unknown message"
    assert summarise({"type": "reaction", "from": "Asha", "emoji": "👍", "to": "42"}) == "unknown message"
    assert summarise({"type": "poll", "from": "Asha"}) == "unknown message"


def test_not_a_dictionary():
    """treats anything that is not a dictionary as unknown"""
    assert summarise(["text", "Asha", "Hello"]) == "unknown message"
    assert summarise("Hello") == "unknown message"
    assert summarise(None) == "unknown message"


def test_uses_match():
    """uses a match statement"""
    source = Path(__file__).with_name("chat.py").read_text(encoding="utf-8")
    assert any(isinstance(node, ast.Match) for node in ast.walk(ast.parse(source)))
A hint

Write one case for each kind of message, as a mapping pattern with the keys it needs, such as case {"type": "join", "user": str(name)}:. A pattern like str(name) fits only a string and captures it; int(number) does the same for whole numbers, and [int(width), int(height)] fits a list of exactly two of them. Put the leave message with a reason above the one without: a mapping pattern ignores extra keys, so the shorter pattern would also fit the longer message.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Then try the practice session. It asks about one kind of pattern at a time, starting with the kind you are least sure of, and every choice explains itself as soon as you check your answer:

Practice that adapts to you

Practise this lesson

16 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 16 What does this print?

    Read the code, then choose one answer.

    match "go":
        case [first, second]:
            print("two items:", first, second)
        case str(text):
            print("text:", text)
    Show the answer: Question 1 of 16

    Answer: text: go

    Sequence patterns never match a string (nor bytes or bytearray), although a string is a sequence of characters elsewhere in Python. So the first case fails and str(text) fits, capturing the whole string.

  2. Question 2 of 16 Which of these subjects does case [first, *rest]: match?

    Choose every answer that is right.

    Show the answer: Question 2 of 16

    Answer:

    • (1, 2, 3)
    • [1]

    The pattern needs a sequence with at least one item: [1] gives rest == [], and the tuple gives rest == [2, 3] (the starred name always gets a list). An empty list has no first item, a string is never matched by a sequence pattern, and a dictionary is a mapping, not a sequence.

  3. Question 3 of 16 A user types todo done 3 4. What does todo(["done", "3", "4"]) return?

    Choose one answer.

    Show the answer: Question 3 of 16

    Answer: not understood: done followed by ['3', '4']

    Fixed-length patterns compare the length first: ["done", number] needs two items and gets three. The variable-length pattern [command, *rest] fits, so the user is told the command was not understood.

  4. Question 4 of 16 Does case {"type": "ping"}: match the subject {"type": "ping", "id": 7}?

    Choose one answer.

    Show the answer: Question 4 of 16

    Answer: Yes, because a mapping pattern ignores keys it does not mention

    A mapping pattern checks only the keys it names, and the subject may have any others. To insist on no other keys, capture them with **rest and add a guard such as if not rest.

  5. Question 5 of 16 Which subjects does the pattern case {}: match?

    Choose one answer.

    Show the answer: Question 5 of 16

    Answer: Any dictionary, with or without keys

    {} names no keys, so every mapping has all the keys it asks for. To match only an empty dictionary, add a guard that tests the subject: for a subject called settings, case {} if not settings:.

  6. Question 6 of 16 A handler must accept {"type": "ping"} but not {"type": "ping", "id": 7}. Which case does that?

    Choose one answer.

    Show the answer: Question 6 of 16

    Answer: case {"type": "ping", **rest} if not rest:

    No mapping pattern on its own rejects extra keys. Collect them with **rest and test them in a guard: the case runs only when rest is empty.

  7. Question 7 of 16 What does @dataclass give the class Rectangle that makes case Rectangle(w, h): work?

    Choose one answer.

    Show the answer: Question 7 of 16

    Answer: __match_args__, set to its field names in order

    A positional sub-pattern needs to know which attribute it stands for. A data class answers with __match_args__, the names of its fields in the order they are declared.

  8. Question 8 of 16 What does plain_class.py print on its standard output before it stops with an error?

    What does this program print? Choose one answer.

    class Version:
        def __init__(self, major, minor):
            self.major = major
            self.minor = minor
    
    
    version = Version(3, 14)
    
    match version:
        case Version(major=3, minor=minor):
            print(f"keyword pattern: Python 3.{minor}")
    
    match version:
        case Version(3, minor):
            print(f"positional pattern: Python 3.{minor}")
    Show the answer: Question 8 of 16

    Answer: it prints

    keyword pattern: Python 3.14

    Keyword patterns read attributes, which works for any class. The positional pattern Version(3, minor) needs __match_args__ to know which attributes the positions mean; Version has none, so Python raises a TypeError before the second message is printed.

  9. Question 9 of 16 case Point(x=0): meets an object of class Point that has no attribute x. What happens?

    Choose one answer.

    Show the answer: Question 9 of 16

    Answer: The pattern fails, and Python tries the next case

    For each keyword pattern Python looks the attribute up on the subject. If it is missing, the class pattern has failed, and the match goes on to the next case.

  10. Question 10 of 16 Which of these subjects does case int(n): fit?

    Choose every answer that is right.

    Show the answer: Question 10 of 16

    Answer:

    • 3
    • True

    int(n) fits any object for which isinstance(subject, int) is True: every int, and True and False as well. Text and floats do not fit, because a pattern never converts its subject.

  11. Question 11 of 16 What does type_patterns.py print?

    What does this program print? Choose one answer.

    import json
    
    
    def x_of(event):
        match event:
            case {"x": int(x)}:
                return f"x is {x}"
            case _:
                return "no whole-number x"
    
    
    def x_of_checked(event):
        match event:
            case {"x": bool()}:
                return "x is true or false"
            case {"x": int(x)}:
                return f"x is {x}"
            case _:
                return "no whole-number x"
    
    
    # The same key four times, as JSON: a number, true, text and a number with a decimal point.
    for line in ['{"x": 120}', '{"x": true}', '{"x": "120"}', '{"x": 120.0}']:
        event = json.loads(line)
        print(f"{line:<13} {x_of(event):<18} {x_of_checked(event)}")
    Show the answer: Question 11 of 16

    Answer: it prints

    {"x": 120}    x is 120           x is 120
    {"x": true}   x is True          x is true or false
    {"x": "120"}  no whole-number x  no whole-number x
    {"x": 120.0}  no whole-number x  no whole-number x

    int(x) checks the type of the value under "x". JSON's true becomes True, which is an int as far as isinstance() is concerned, so x_of() takes it for a whole number; x_of_checked() catches it first with bool(). Text and floats never fit.

  12. Question 12 of 16 What does key hold once case {"type": "key", "key": ("Enter" | "Tab") as key}: has fitted {"type": "key", "key": "Tab"}?

    Choose one answer.

    Show the answer: Question 12 of 16

    Answer: 'Tab'

    ("Enter" | "Tab") as key first checks that the value is one of the two strings, then binds it to key, so the case block knows which key it was.

  13. Question 13 of 16 Which of these subjects does {"type": "resize", "size": [int(width), int(height)]} fit?

    Choose every answer that is right.

    Show the answer: Question 13 of 16

    Answer:

    • {"type": "resize", "size": (800, 600)}
    • {"type": "resize", "size": [1280, 720], "dpr": 2}

    A nested pattern fits when each of its parts does: a mapping with both keys, the literal "resize", a sequence of two items (a list or a tuple) and two ints.

  14. Question 14 of 16 What does describe() from events.py return for {"type": "scroll", "dy": 0}?

    Choose one answer.

    Show the answer: Question 14 of 16

    Answer: scroll down 0 lines

    Both scroll cases have the same pattern; the first adds the guard dy < 0. For 0 the guard is False, so Python tries the next case, and the scroll-down case returns "scroll down 0 lines".

  15. Question 15 of 16 The JSON line {"type": "key", "key": "Enter", "ctrl": true} reaches describe() through json.loads(). What does it return?

    Choose one answer.

    Show the answer: Question 15 of 16

    Answer: shortcut Ctrl+ENTER

    Python tries the cases from the top and runs the first that fits. The shortcut case needs a str key and ctrl equal to True, and this event has both, so it answers before the Enter case is reached.

  16. Question 16 of 16 The case {"type": str(kind), **rest} is moved to the top of describe(). What happens?

    Choose one answer.

    Show the answer: Question 16 of 16

    Answer: Every event with a text type is reported as one it cannot handle; the click, key, scroll and resize cases never run

    Order decides: the first case that fits wins. Put the shapes of the events you know first, the general case after them, and case _ last.

Interview questions

Fresher · What does each of the three structural patterns check before it captures anything?

A sequence pattern such as [first, *rest] checks that the subject is a sequence, but not a str, bytes or bytearray, then its length: exactly as many items as it has sub-patterns, or at least the ones that are not starred. Then it matches the items from the left. A mapping pattern such as {"host": host} checks that the subject is a mapping with at least the keys it names; other keys are ignored, so {} fits every dictionary. A class pattern such as Rectangle(w, h) checks isinstance() first, then reads one attribute per sub-pattern, using __match_args__ to turn positions into attribute names; for int, str and the other listed built-in types, one positional pattern matches the whole value. When every part fits, all the names are bound and the guard, if there is one, decides.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A payment service sends webhook events as JSON: captured payments, failed payments and refunds, each with its own keys. Amounts sometimes arrive as text, and fields go missing. Replace a long chain of if and isinstance() checks with one match statement. How do you order the cases, and what happens to an event that no case fits?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    A service matches Order(order_id, total) positionally in a dozen places. A teammate reorders the data class's fields to total first, then order_id, for a nicer repr. No error appears, but some reports are now wrong. Why, and how do you make these patterns safe against the next change?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • [a, b] fits a sequence of exactly two items and [first, *rest] one of at least one; rest is always a list. Strings, bytes and bytearrays never match sequence patterns.
  • {"key": pattern} fits a mapping that has at least that key; other keys are ignored, **rest collects them, and {} fits every dictionary.
  • Class(attr=pattern) checks isinstance() and the attributes; the positional form needs __match_args__, which data classes set for you.
  • int(n), str(s) and the other built-in types match the whole value, which checks its type, and int(n) lets True and False in; as name captures a part that a pattern also describes.
  • Put specific shapes before general ones, and end with a case for data that fits none of them.

Terms in this lesson

__match_args__
A class attribute holding a tuple of attribute names. It tells a class pattern which attribute each positional sub-pattern stands for; @dataclass sets it to the fields in the order they are declared.
as pattern
A pattern followed by as and a plain name, such as ("Enter" | "Tab") as key. When the pattern fits, the name is bound to the value it matched.
class pattern
A pattern written like a call, such as Circle(radius=r). It fits an instance of the class, tested with isinstance(), whose attributes match the patterns given for them.
mapping pattern
A pattern written like a dict, such as {"host": host}. It fits a mapping that has at least the keys it names and ignores the others; **rest collects them, and {} fits every mapping.
sequence pattern
A pattern written like a list or a tuple, such as [first, *rest]. It fits a sequence of the right length, but never a str, bytes or bytearray, and matches each item against the pattern in its place.
structural pattern matching
Testing a value by its shape, such as a list of two items or a dict with a "host" key, and capturing its parts in the same step, as a match statement does with sequence, mapping and class patterns.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.