Python Conditions · Lesson 32 of 149

Python match Statement

What you will learn

  • The match and case statement, and when it beats if / elif
  • Literal patterns, the wildcard _ and OR patterns with |
  • Capturing values from lists and tuples, including *rest
  • Matching dictionaries, types and objects
  • Guards (case ... if ...) and as
  • The pitfall: a bare name captures instead of comparing

match was added in Python 3.10. It does not exist in older versions, so check your version with python --version (lesson 1.1). It is called structural pattern matching, and it goes far beyond a "switch" statement in other languages.

1. The basic form

match takes one subject value and tries each case pattern from top to bottom. The block of the first pattern that fits runs, and the rest are skipped:

def http(status):
    match status:
        case 200:
            return "ok"
        case 301 | 302:
            return "redirect"
        case 404:
            return "not found"
        case _:
            return "other"

print([http(s) for s in [200, 302, 404, 500]])
['ok', 'redirect', 'not found', 'other']
  • case 200: matches a literal value.
  • case 301 | 302: is an OR pattern: either value matches.
  • case _: is the wildcard. It matches anything, so it works like else. Put it last.

If no case matches and there is no wildcard, nothing happens and the program continues:

match 5:
    case 1:
        print("one")
print("no match: nothing happened")
no match: nothing happened

(def and return are covered in chapter 11.)

Quick check: which case runs for `status = 302` in the function above?

case 301 | 302, which returns "redirect".

2. Literals you can match

Patterns can be numbers, strings, None, True and False. None, True and False are compared by identity (like is), so case True: matches True but not 1:

match "hello":
    case "hello" | "hi" as greeting:
        print("greeted with", greeting)
greeted with hello

The as keyword gives a name to whatever the pattern matched.

3. Capturing from sequences

A pattern shaped like a list or tuple matches a sequence of that shape and captures parts into names:

def command(text):
    match text.split():
        case ["quit"]:
            return "bye"
        case ["go", direction]:
            return f"going {direction}"
        case ["pick", item, *more]:
            return f"pick {item} and {len(more)} more"
        case []:
            return "empty"
        case _:
            return "unknown"

for t in ["quit", "go north", "pick key lamp rope", "", "dance now"]:
    print(repr(t), "->", command(t))
'quit' -> bye
'go north' -> going north
'pick key lamp rope' -> pick key and 2 more
'' -> empty
'dance now' -> unknown
  • ["go", direction] needs exactly two items, the first equal to "go". The second is captured into direction.
  • ["pick", item, *more] needs at least two items, and *more collects the rest into a list.
  • [] matches an empty sequence.

Square brackets and round brackets mean the same in a pattern: both match any list or tuple (but not a string). Patterns can nest: case [a, [b, c]]:.

4. Guards

A guard is an extra if after the pattern. The case matches only if the pattern fits and the guard is true:

def point(p):
    match p:
        case (0, 0):
            return "origin"
        case (0, y):
            return f"on the y axis at {y}"
        case (x, 0):
            return f"on the x axis at {x}"
        case (x, y) if x == y:
            return f"on the diagonal at {x}"
        case (x, y):
            return f"at {x}, {y}"

print([point(p) for p in [(0, 0), (0, 5), (3, 0), (4, 4), (1, 2)]])
['origin', 'on the y axis at 5', 'on the x axis at 3', 'on the diagonal at 4', 'at 1, 2']

The names x and y are filled in before the guard is checked, so the guard can use them.

5. Dictionaries

A dictionary pattern checks that certain keys are present with matching values. Extra keys are ignored, and **rest collects them:

def config(c):
    match c:
        case {"mode": "dark", **rest}:
            return f"dark, extras {rest}"
        case {"mode": m}:
            return f"mode {m}"
        case {}:
            return "any dict"

print(config({"mode": "dark", "size": 3}))
print(config({"mode": "light"}))
print(config({"x": 1}))
dark, extras {'size': 3}
mode light
any dict

Notice that case {} matches any dictionary, because it asks for no keys at all.

6. Types and objects

A class pattern such as int() checks the type. With names inside the brackets, it also looks at the object's attributes (classes are covered in chapter 13):

def kind(v):
    match v:
        case None:
            return "none"
        case True:
            return "true"
        case int():
            return "int"
        case float():
            return "float"
        case str() as s if s.isdigit():
            return "digit string"
        case str():
            return "string"
        case [_, _]:
            return "pair"
        case _:
            return "other"

print([kind(v) for v in [None, True, 5, 2.5, "42", "hi", [1, 2], {1}]])
['none', 'true', 'int', 'float', 'digit string', 'string', 'pair', 'other']

Order matters: case True comes before case int(), because True is also an int.

For your own classes, match attributes by name:

from dataclasses import dataclass

@dataclass
class P:
    x: int
    y: int

def where(p):
    match p:
        case P(x=0, y=0):
            return "origin"
        case P(x=0):
            return "y axis"
        case P(x, y):
            return f"{x},{y}"

print(where(P(0, 0)), where(P(0, 3)), where(P(1, 2)))
origin y axis 1,2

(@dataclass is lesson 13.11. The positional form P(x, y) works because dataclasses define the order of their fields.)

7. The pitfall: a bare name captures

In a pattern, a plain name is not a comparison. It is a capture: it matches anything and stores the value in that name:

RED = "red"

def bad(c):
    match c:
        case RED:
            return "matched RED"

print(bad("blue"))
matched RED

The value "blue" was captured into the name RED, so the case matched. To compare against a named constant, write a dotted name, such as a member of an enum (lesson 13.12), which Python reads as a value:

import enum

class Color(enum.Enum):
    RED = "red"
    BLUE = "blue"

def colour(c):
    match c:
        case Color.RED:
            return "is red"
        case Color.BLUE:
            return "is blue"

print(colour(Color.BLUE), colour("red"))
is blue None

Python protects you from the worst case: a bare-name case followed by other cases is a syntax error, SyntaxError: name capture 'RED' makes remaining patterns unreachable.

8. match is a soft keyword

match and case only act as keywords in this statement. They are still allowed as ordinary names, so older code such as match = 3 keeps working.

9. match or if?

Use Choose
comparing one value with a few constants match or if / elif
taking apart lists, tuples and dictionaries match
different handling by type or shape match
simple true/false tests, ranges if / elif
code that must run on Python before 3.10 if / elif

Worked example: a tiny calculator command

Read commands such as "add 3 4", "neg 5" or "quit".

def calc(line):
    match line.split():
        case ["add", a, b]:
            return int(a) + int(b)
        case ["neg", a]:
            return -int(a)
        case ["quit"]:
            return "bye"
        case [word, *_]:
            return f"unknown command: {word}"
        case _:
            return "empty line"

for line in ["add 3 4", "neg 5", "quit", "pow 2 3", ""]:
    print(repr(line), "->", calc(line))
'add 3 4' -> 7
'neg 5' -> -5
'quit' -> bye
'pow 2 3' -> unknown command: pow
'' -> empty line
Pattern Matches
["add", a, b] exactly three words starting with add
["neg", a] two words starting with neg
[word, *_] any other non-empty line; *_ ignores the rest
_ whatever is left (the empty line)

The commands are made up for the example.

Common mistakes

  • Using a bare name as a constant. It captures. Use a literal, or a dotted name such as Color.RED.
  • Forgetting the wildcard _ when you want a default.
  • Putting a general pattern before a specific one. The first match wins.
  • Running on Python older than 3.10.
  • Expecting case True to match 1. It does not; True is compared by identity.
  • Matching strings as sequences. A string never matches a list pattern.

Key takeaways

  • match subject: followed by case pattern: blocks; the first pattern that fits runs.
  • _ is the wildcard; a | b is an OR pattern; pattern as name names the match; case ... if cond adds a guard.
  • Sequence and dictionary patterns capture parts of the data; *rest and **rest collect extras.
  • Class patterns such as int() or P(x=0) match by type and attributes.
  • A bare name in a pattern captures; compare with constants by dotted names. Needs Python 3.10 or later.

Practice

1. Write a match that gives "weekend" for "sat" or "sun" and "weekday" for anything else.

Show answer
match day:
    case "sat" | "sun":
        print("weekend")
    case _:
        print("weekday")

2. What does case [first, *rest]: match, and what do the names hold for [1, 2, 3]?

Show answer

Any non-empty list or tuple. first is 1 and rest is [2, 3].

3. Why does case MAX: (where MAX = 10) match every value?

Show answer

A bare name in a pattern is a capture: it matches anything and stores the value in MAX. It does not compare with the old value 10.

4. Add a guard so that case (x, y) only matches when x > y.

Show answer

case (x, y) if x > y:.

5. In what order must case True: and case int(): be written, and why?

Show answer

case True: first. True is also an int, so case int(): would catch it before the True case could.

6. Which Python version is needed for match, and how can you check yours?

Show answer

Python 3.10 or later. Check with python --version in a terminal.