Reading history

Python match-case Statement (Pattern Matching)

6 min read 2 views

Learn Python's match-case statement: literal and or patterns, captures and guards, sequence, class and mapping patterns, the _ wildcard and common mistakes.

Python 3.10 added the match statement, often called structural pattern matching. At its simplest it replaces a long chain of if/elif comparisons. Its real power is that a pattern can also unpack data: pull words out of a command, fields out of an object, or values out of a dictionary, all while checking its shape. This lesson covers literal, sequence, class and mapping patterns, guards and the wildcard.

In this lesson you will learn

  • The basic match/case syntax and the _ wildcard
  • Matching several values with |
  • Capturing values and adding if guards
  • Sequence patterns for lists and tuples
  • Class patterns and mapping (dictionary) patterns

You should know if/else, functions and dictionaries. You need Python 3.10 or later.

Values, Sequences and Guards

# match-case compares a value against patterns, top to bottom
def http_status(code):
    match code:
        case 200:
            return "OK"
        case 301 | 302:                 # either value
            return "Redirect"
        case 404:
            return "Not Found"
        case n if 500 <= n < 600:       # capture + guard condition
            return f"Server error {n}"
        case _:                          # wildcard: anything else
            return "Unknown"

for c in [200, 302, 404, 503, 418]:
    print(c, "->", http_status(c))


# Sequence patterns unpack lists and tuples
def command(text):
    match text.split():
        case ["quit"]:
            return "Goodbye"
        case ["go", direction]:
            return f"Moving {direction}"
        case ["take", *items]:
            return f"Taking {', '.join(items)}"
        case []:
            return "Say something"
        case _:
            return f"Unknown command: {text!r}"

for t in ["go north", "take pen notebook", "quit", "", "dance now"]:
    print(command(t))

Output

200 -> OK
302 -> Redirect
404 -> Not Found
503 -> Server error 503
418 -> Unknown
Moving north
Taking pen, notebook
Goodbye
Say something
Unknown command: 'dance now'
  • match code: takes a subject, and each case is tried from top to bottom. The first pattern that fits wins, and the rest are skipped. There is no fall-through, so no break is needed.
  • case 301 | 302: matches either value.
  • case n if 500 <= n < 600: captures the value into the name n, then the guard after if must also be true.
  • case _: is the wildcard. It always matches, so it belongs last, like else.
  • Sequence patterns check the length and unpack in one step. ["go", direction] matches a two-word list starting with “go” and stores the second word. ["take", *items] collects any number of remaining words.
  • [] matches an empty list, so an empty command gets its own message.

Class and Mapping Patterns

from dataclasses import dataclass


@dataclass
class Circle:
    r: float


@dataclass
class Rect:
    w: float
    h: float


def area(shape):
    match shape:
        case Circle(r=r):                       # class pattern
            return round(3.14159 * r * r, 2)
        case Rect(w=w, h=h) if w == h:          # a square
            return f"square of {w * h}"
        case Rect(w=w, h=h):
            return w * h
        case _:
            raise TypeError(f"not a shape: {shape!r}")


print(area(Circle(2)), area(Rect(3, 3)), area(Rect(2, 5)))

# Mapping patterns match dictionaries, e.g. parsed JSON
events = [
    {"type": "login", "user": "nusrat"},
    {"type": "order", "user": "arif", "amount": 450},
    {"type": "order", "user": "rina", "amount": 2600},
    {"type": "logout"},
]
for e in events:
    match e:
        case {"type": "login", "user": str(name)}:
            print(f"{name} logged in")
        case {"type": "order", "amount": int(a)} if a > 1000:
            print(f"large order: {a} taka from {e['user']}")
        case {"type": "order", "user": name}:
            print(f"order from {name}")
        case {"type": other}:
            print(f"ignored event: {other}")

Output

12.57 square of 9 10
nusrat logged in
order from arif
large order: 2600 taka from rina
ignored event: logout
  • case Circle(r=r): is a class pattern. It checks that the subject is a Circle and pulls out its r attribute.
  • Order matters: the guarded square case comes before the general rectangle case, otherwise every rectangle, including squares, would match the general one first.
  • Mapping patterns such as {"type": "login", "user": str(name)} match dictionaries that contain at least those keys. Extra keys are allowed, which suits JSON data from an API.
  • str(name) and int(a) check the type and capture the value at the same time.
  • Rina’s order of 2600 matched the “large order” case; Arif’s 450 failed its guard and fell through to the general order case.

Pattern Types

PatternExampleMatches
Literalcase 404:An equal value
Orcase "y" | "yes":Any of the alternatives
Capturecase x:Anything, and binds it to x
Wildcardcase _:Anything, without binding
Sequencecase [first, *rest]:Lists and tuples of a matching length
Mappingcase {"id": i}:Dictionaries containing those keys
Classcase Point(x=0):Instances with matching attributes
Guardcase n if n > 0:Any pattern plus an extra condition

Common Mistakes

  1. Matching against a variable: case limit: does not compare with a variable called limit; it captures anything into a new name. Use a dotted name such as case Status.OK:, or a guard.
  2. Putting the wildcard or a broad pattern first, so later cases can never run.
  3. Using match for a simple two-way choice, where if/else is clearer.
  4. Expecting strings to match as sequences. A string does not match [a, b]; split it first, as the command example does.

Practice Exercises

Exercise 1. Write grade(mark) using match with guards: 80 and above “A+”, 70–79 “A”, 60–69 “B”, anything else “F”.

Show answer
def grade(mark):
    match mark:
        case m if m >= 80:
            return "A+"
        case m if m >= 70:
            return "A"
        case m if m >= 60:
            return "B"
        case _:
            return "F"

print(grade(85), grade(72), grade(40))   # A+ A F

Exercise 2. Match a point given as a tuple (x, y) and print “origin”, “on the x-axis”, “on the y-axis” or “elsewhere”.

Show answer
def where(point):
    match point:
        case (0, 0):
            return "origin"
        case (x, 0):
            return "on the x-axis"
        case (0, y):
            return "on the y-axis"
        case _:
            return "elsewhere"

print(where((0, 0)), where((5, 0)), where((0, -2)), where((3, 4)))

Frequently Asked Questions

Is match-case the same as switch in other languages?

It covers what a switch does, but it is more powerful: it can unpack sequences, dictionaries and objects, bind variables and check types. It also never falls through from one case to the next.

Is match faster than if/elif?

Not noticeably for most code. Choose match when it makes the code clearer, especially when you are checking the shape of data rather than a single value.

Summary

  • match tries each case in order and runs the first that fits.
  • Patterns can compare, capture, unpack and check types.
  • Guards add extra conditions; _ catches everything else.
  • A bare name in a pattern captures; it never compares with an existing variable.

Next: Python Built-in Functions.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *