Browse topics

match statement

Version
3.14
Since
3.10
Review
Draft

Summary#

match compares a value against patterns in order and runs the first case that succeeds. Patterns can test shapes of sequences, mappings and objects, bind parts to names and add an if guard.

Syntax#

python
match subject:
    case ["move", x, y] if x == y:
        pass
    case {"type": "key", "code": code}:
        pass
    case Point(x=0) | None:
        pass
    case _:
        pass

Example#

python
from dataclasses import dataclass


@dataclass
class Point:
    x: int
    y: int


def describe(event):
    match event:
        case {"type": "key", "code": str(code)}:
            return f"key {code}"
        case ["move", x, y] if x == y:
            return f"diagonal {x}"
        case ["move", *steps]:
            return f"move {steps}"
        case Point(x=0, y=y):
            return f"axis point {y}"
        case "quit" | "exit":
            return "bye"
        case _:
            return "unknown"


events = [
    {"type": "key", "code": "Esc", "repeat": False},
    ["move", 2, 2],
    ("move", 1, 3),
    Point(0, 5),
    "exit",
    42,
]
for event in events:
    print(describe(event))

Expected output#

Text
key Esc
diagonal 2
move [1, 3]
axis point 5
bye
unknown

Common mistakes#

A bare name in a pattern captures the value. As the last case, case LIMIT: matches anything and binds LIMIT in the current scope. That unguarded case before other cases is a syntax error. Compare with a dotted name such as case Status.READY:, or use a guard. Sequence patterns exclude str, bytes and bytearray.

Version applicability#

The match statement was added in Python 3.10. Earlier versions raise a syntax error. match and case are soft keywords, so they remain usable as ordinary names elsewhere.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0