Control Flow

Advanced Match Patterns

match patterns can destructure sequences, combine alternatives, and add guards.

Sequence patterns match by position. A guard after if adds a condition that must also be true.

Source

def describe(command):
    match command:
        case ["move", x, y] if x >= 0 and y >= 0:
            return f"move to {x},{y}"
        case ["quit" | "exit"]:
            return "stop"
        case ["echo", *words]:
            return " ".join(words)
        case _:
            return "unknown"

print(describe(["move", 2, 3]))

Output

move to 2,3
capture[x, y]alternativeP() | Q()guard[x] if x > 0classPoint(x=0, y=_)
Capture, alternative, guard, and class patterns each name a different way a value can match a case.

An OR pattern accepts several alternatives in one case. A star pattern captures the rest of a sequence.

Source

print(describe(["exit"]))
print(describe(["echo", "hello", "python"]))

Output

stop
hello python

The wildcard _ catches values that did not match earlier cases. Here the guard rejects the negative coordinate.

Source

print(describe(["move", -1, 3]))

Output

unknown

Notes

See also

Run the complete example

Example code

Expected output

move to 2,3
stop
hello python
unknown

Execution time appears here after you run the example.