match, case

Pattern matching: choosing a branch of code based on a value’s data and shape.

On this page

Example

#
Python
def handle(command):
    match command.split():
        case ["start"]:
            return "Starting the lesson"
        case ["go", direction]:
            return f"Heading {direction}"
        case ["score", *values] if values:
            return f"Total: {sum(map(int, values))}"
        case _:
            return "Unknown command"

print(handle("start"))
print(handle("go north"))
print(handle("score 10 20 5"))
print(handle("fly"))
Resultsaved result, you can check it
Starting the lesson
Heading north
Total: 35
Unknown command

Definition and usage

#

The match statement (since Python 3.10) compares a value against successive patterns in case blocks and runs the first one that matches. The pattern case _: matches anything and works like else.

In simple uses it resembles switch from other languages. Its real strength, though, lies in matching structure: you can unpack tuples, lists, and dictionaries, combine patterns with |, and add if conditions.

Matching by a bare variable name works like an assignment, not a comparison. To compare against a constant, use literals or dotted names, for example Color.RED.

Syntax

#
Syntax
match value:
    case pattern:
        ...
    case _:
        ...

More examples

#
Matching dictionaries
Python
event = {"type": "exercise", "exp": 20}

match event:
    case {"type": "exercise", "exp": exp}:
        print(f"+{exp} EXP for the exercise")
    case {"type": "login"}:
        print("Welcome back")
Resultsaved result, you can check it
+20 EXP for the exercise

Good practices

#
  • Always add a case _: branch to handle unexpected values.
  • For a simple comparison against a few values, a dictionary can be shorter than match.

Related entries

#

Spotted a mistake or missing an example? Write to us.