Structural Pattern Matching

Published by Brayan K

Structural pattern matching is Python's match/case statement (3.10+) that branches on the shape of data — the structure of a list, dict, or object — while pulling out its pieces in the same step.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Choose a branch by the shape of a command

A pattern describes the shape and values you expect. Python tries cases from top to bottom and runs the first case whose pattern and optional condition succeed. This command handler distinguishes a command with one argument from a command with none. A tuple can match a sequence pattern written with square brackets; the brackets describe a pattern, not a conversion to a list.

commands = [("open", "notes"), ["quit"], ["open"], "quit"]
for command in commands:
    match command:
        case ["open", name]:
            print("opening", name)
        case ["quit"]:
            print("closing")
        case _:
            print("unsupported")

# ✅ Expected output:
# opening notes
# closing
# unsupported
# unsupported

The final underscore is a wildcard: it accepts anything without storing it. Sequence patterns do not split strings or bytes into characters. A sequence with the wrong number of items simply fails that pattern, so another case can handle it; this differs from an unpacking assignment that raises an exception.

Ordinary conditions belong to Control Flow: Making Decisions in Python. Assignment targets and starred collection are developed in Unpacking & Star Expressions; here they are used to describe a match.

A bare name saves the subject; it does not compare

Writing an existing variable name after case does not ask whether the subject equals that variable. It captures the subject and rebinds the name. That includes names written in capitals: naming a variable like a constant does not turn it into a value pattern.

expected = "open"
match "close":
    case expected:
        print("captured:", expected)
print("after match:", expected)

# ✅ Expected output:
# captured: close
# after match: close

Use a literal for a fixed value. To compare with a runtime variable, capture a different name and use a guard. A dotted name such as Commands.OPEN is a value pattern, but a bare OPEN is still a capture.

expected = "open"
for command in ["close", "open"]:
    match command:
        case actual if actual == expected:
            print("accepted", actual)
        case _:
            print("different command")
print("expected:", expected)

# ✅ Expected output:
# different command
# accepted open
# expected: open

An unguarded capture or wildcard would prevent any later case from being reached. Python rejects that arrangement before running the program. Move the catch-all to the end, as in the examples above.

match "open":
    case _:
        print("anything")
    case "open":
        print("opening")

# ✅ Expected error:
# SyntaxError: wildcard makes remaining patterns unreachable

Require the fields you need, then test their values

A mapping pattern requires the named keys but normally tolerates extra keys. Capturing the value of a key does not validate its type. Here the missing amount is rejected by the shape, but a text amount reaches the guard and raises an error; guard exceptions do not mean “try the following case”.

event = {"kind": "credit", "amount": "ten"}
match event:
    case {"kind": "credit", "amount": amount} if amount > 0:
        print("accepted")
    case _:
        print("rejected")

# ✅ Expected error:
# TypeError: '>' not supported between instances of 'str' and 'int'

Use a type pattern before an operation that needs that type. The guard below also excludes bool, because bool is a subclass of int. Extra mapping fields are harmless here; when your format forbids them, collect them with **extra and require that dictionary to be empty.

events = [
    {"kind": "credit", "amount": 5, "source": "desk"},
    {"kind": "credit", "amount": "ten"},
    {"kind": "credit"},
    {"kind": "credit", "amount": True},
]
for event in events:
    match event:
        case {"kind": "credit", "amount": int() as amount} if type(amount) is int and amount > 0:
            print("credit", amount)
        case _:
            print("rejected")

# ✅ Expected output:
# credit 5
# rejected
# rejected
# rejected

A guard runs only after its pattern has matched. A false guard lets Python try the remaining cases. Names from a successful match remain available afterwards, but do not depend on bindings left by a failed pattern; keep each branch responsible for its own values.

Give alternative patterns the same captured names

The vertical bar means alternative patterns, not a boolean expression or a bitwise calculation. Both alternatives must bind the same names so the branch has a consistent set of values. The as pattern can capture a matched value while also restricting it to particular literals.

for command in [["load", "draft"], ["open", "report"], ["stop"]]:
    match command:
        case ["load" | "open", name]:
            print("document", name)
        case ["stop" | "quit" as action]:
            print("action", action)
        case _:
            print("unknown")

# ✅ Expected output:
# document draft
# document report
# action stop
match ["open", "notes"]:
    case ["open", name] | ["load", filename]:
        print(name)

# ✅ Expected error:
# SyntaxError: alternative patterns bind different names

Use name in both alternatives, or factor the alternatives into the command position as in the working example. The branch then has one predictable name to read.

A class pattern inspects an existing object

A class pattern does not call a constructor. It checks the object against the class and then matches attributes. Keyword patterns name those attributes directly; class construction itself is covered by Object-Oriented Programming (OOP) in Python 🧠.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

for point in [Point(0, 4), Point(2, 3), (0, 4)]:
    match point:
        case Point(x=0, y=height):
            print("vertical", height)
        case Point(x=x, y=y):
            print("point", x, y)
        case _:
            print("not a Point")

# ✅ Expected output:
# vertical 4
# point 2 3
# not a Point

Positional class patterns need a declared mapping from positions to attribute names. Python does not infer that mapping from __init__ parameter names. The class below has no __match_args__, so its positional pattern fails with a TypeError.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

match Point(2, 3):
    case Point(x, y):
        print(x, y)

# ✅ Expected error:
# TypeError: Point() accepts 0 positional sub-patterns (2 given)
class Point:
    __match_args__ = ("x", "y")
    def __init__(self, x, y):
        self.x = x
        self.y = y

match Point(2, 3):
    case Point(x, y):
        print(x, y)

# ✅ Expected output:
# 2 3

Capture a command with any number of tags

Complete the starred capture and guard. A tag command needs a document name and at least one tag. The star captures remaining items as a list, including an empty list when no tags follow. Keep the wildcard branch so unsupported commands get an explicit response.

for command in [["tag", "draft", "urgent", "review"], ["tag", "draft"]]:
    match command:
        case ["tag", name, ___] if ___:
            print(name, tags)
        case _:
            print("no tags supplied")

# 👉 replace ___ with *tags
# 👉 replace ___ with tags

# ✅ Expected output:
# draft ['urgent', 'review']
# no tags supplied

Build a small message router

Process the four messages in the solution data. Accept a rename only when it contains exactly three sequence items and the new name is a non-blank string; print its stripped form. Accept either one-item stop command spelling. Everything else should print unsupported. Write the cases before opening the solution, and put the fallback last.

messages = [["rename", "draft", " final "], ["rename", "draft", "  "], ["quit"], ["rename"]]
for message in messages:
    match message:
        case ["rename", old, str() as new] if new.strip():
            print("rename", old, "to", new.strip())
        case ["quit" | "stop"]:
            print("stop")
        case _:
            print("unsupported")

# ✅ Expected output:
# rename draft to final
# unsupported
# stop
# unsupported

Practice quiz

What does this program print? wanted = "yes" match "no": case wanted: print(wanted)

  • yes
  • no
  • False
  • SyntaxError

Answer: no. A bare name captures the subject, replacing the earlier value.

What does this program print? match "ab": case [a, b]: print(a, b) case _: print("other")

  • a b
  • ['a', 'b']
  • TypeError
  • other

Answer: other. String subjects are excluded from sequence patterns.

What does this program print? match {"x": 2, "y": 3}: case {"x": n}: print(n) case _: print("other")

  • 2
  • other
  • 2 3
  • KeyError

Answer: 2. A mapping pattern can match a subset of the keys.

What does this program print? match ["open", "draft"]: case ["load" | "open", name]: print(name) case _: print("other")

  • open
  • other
  • draft
  • SyntaxError

Answer: draft. The alternative applies to the first item; name captures the second.

What does this program print? match -2: case n if n > 0: print("positive") case n: print("remaining", n)

  • positive
  • remaining -2
  • remaining 0
  • nothing

Answer: remaining -2. A false guard lets matching continue to the next case.

What does this program print? match ("tag", "draft"): case ["tag", name, *tags]: print(name, tags)

  • draft None
  • draft ()
  • ValueError
  • draft []

Answer: draft []. The star receives an empty list when no remaining items exist.

What does this program print? class Item: value = 7 match Item(): case Item(value=n): print(n)

  • 7
  • Item
  • None
  • TypeError

Answer: 7. The keyword pattern reads the existing value attribute.

Which arrangement is valid?

  • An unguarded wildcard followed by a literal case
  • Two OR alternatives that capture different names
  • Specific cases followed by an unguarded wildcard
  • A bare variable pattern that compares with its old value

Answer: Specific cases followed by an unguarded wildcard. The catch-all belongs last; capture patterns bind rather than compare, and alternatives must agree on names.

Continue this course

Related lessons