Control Flow

Match Statements

match selects cases using structural pattern matching.

Use match when the shape of a value is the decision. This command is a dictionary with an action and coordinates; the first case checks that shape and binds x and y.

Source

command = {"action": "move", "x": 3, "y": 4}

match command:
    case {"action": "move", "x": x, "y": y}:
        print(f"move to {x},{y}")

Output

move to 3,4
match valuecase 0:case [x, y]:case Point(0, _):case _:first match
match dispatches by pattern shape; the value flows down the patterns and the first match wins.

Other cases describe other valid shapes. This complete fragment changes the command so the quit case is the first matching pattern.

Source

command = {"action": "quit"}

match command:
    case {"action": "move", "x": x, "y": y}:
        print(f"move to {x},{y}")
    case {"action": "quit"}:
        print("quit")

Output

quit

Broader patterns and the _ catch-all belong after specific cases. This fragment extracts an unknown action before the final fallback would run.

Source

command = {"action": "jump"}

match command:
    case {"action": "move", "x": x, "y": y}:
        print(f"move to {x},{y}")
    case {"action": "quit"}:
        print("quit")
    case {"action": action}:
        print(f"unknown action: {action}")
    case _:
        print("invalid command")

Output

unknown action: jump

Notes

See also

Run the complete example

Example code

Expected output

move to 3,4

Execution time appears here after you run the example.