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.
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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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;wordsgets 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:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- Its block runs. The block returns "added: " + " ".join(words), which is "added: buy milk". That ends the match statement.
- 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
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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- The subject. address({"port": 8080}) reaches the match. The subject is a dictionary with one key, "port", and no "host".
- 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.
- Missing again. {"host": host} asks for one key only, and it is the one the subject lacks, so this case fails too.
- {} 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.
- 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.
- 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
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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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):
The drawing shows the whole scene; its 8 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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).
- 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.
- 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.
- 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.
- 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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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__
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):
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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()
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:
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:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- 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.
- The type is a literal. The value of "type" goes to the literal pattern "resize". The two strings are equal, so this part fits.
- 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.
- 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.
- 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.
- 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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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
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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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": Trueis a literal pattern, compared by identity, so it fits JSON’strueand nothing else.int(x)andint(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:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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'}.
- 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.
- 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
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"}givesAsha: Hello{"type": "image", "from": "Ravi", "size": [640, 480]}givesRavi sent a 640x480 image; the size is a list of exactly two whole numbers, both greater than 0{"type": "join", "user": "Mei"}givesMei joined{"type": "leave", "user": "Mei", "reason": "timeout"}givesMei left (timeout){"type": "leave", "user": "Mei"}, without a reason, givesMei left{"type": "reaction", "from": "Asha", "emoji": "👍", "to": 42}givesAsha 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.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
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.
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.
-
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?
-
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?
Key takeaways
[a, b]fits a sequence of exactly two items and[first, *rest]one of at least one;restis 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,**restcollects them, and{}fits every dictionary.Class(attr=pattern)checksisinstance()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, andint(n)letsTrueandFalsein;as namecaptures 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
- The Python Language Reference: the match statement (Python Software Foundation)
- The Python Tutorial: match statements (Python Software Foundation)
- PEP 634: Structural Pattern Matching: Specification (Python Software Foundation)
- PEP 636: Structural Pattern Matching: Tutorial (Python Software Foundation)
- Data model: customizing positional arguments in class pattern matching (Python Software Foundation)
- dataclasses: the match_args parameter (Python Software Foundation)
- json: how JSON values become Python values (Python Software Foundation)
- Built-in types: bool is a subclass of int (Python Software Foundation)
- What's New In Python 3.14: improved error messages (Python Software Foundation)
- What's New In Python 3.15: other language changes (Python Software Foundation)
- The Python Language Reference 3.15: class patterns (frozendict) (Python Software Foundation)
- RFC 9110: HTTP Semantics, section 4.2.2 (the https scheme) (Internet Engineering Task Force (IETF))
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress