Codectionary / Developer documentation / Python

match / case

Introduced in Python 3.10, the match statement provides structural pattern matching - Python's answer to the switch/case statements found in many other languages, but considerably more powerful. It compares a subject value against a series of case patterns, which can match literal values, capture variables, destructure sequences and dictionaries, and even include guard conditions.

Syntax

match subject:\n    case pattern:\n        # code

Examples

Basic Match Statement

Matching a value against several literal cases, similar to a switch statement.

def describe_status(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Server Error"
        case _:
            return "Unknown Status"

print(describe_status(404))  # Not Found
print(describe_status(999))  # Unknown Status

Matching Multiple Values

Using '|' to match several patterns with the same result.

def classify_day(day):
    match day:
        case "Saturday" | "Sunday":
            return "Weekend"
        case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
            return "Weekday"
        case _:
            return "Invalid day"

print(classify_day("Saturday"))  # Weekend

Matching with Guards

Adding an extra condition to a case with an if guard clause.

def categorize(age):
    match age:
        case n if n < 13:
            return "Child"
        case n if 13 <= n < 20:
            return "Teenager"
        case n if n >= 20:
            return "Adult"

print(categorize(15))  # Teenager

Matching Data Structures

Destructuring sequences and dictionaries directly within a case pattern.

def handle_command(command):
    match command:
        case ["move", direction]:
            return f"Moving {direction}"
        case ["say", *words]:
            return f"Saying: {' '.join(words)}"
        case {"action": "quit"}:
            return "Quitting"
        case _:
            return "Unknown command"

print(handle_command(["move", "north"]))       # Moving north
print(handle_command(["say", "hi", "there"]))  # Saying: hi there
print(handle_command({"action": "quit"}))      # Quitting

Best practices

  • Use match/case when comparing one value against several discrete possibilities - it reads more clearly than a long if/elif chain
  • Always include a case _: wildcard branch to handle values that don't match any specific pattern
  • Remember match/case requires Python 3.10 or later - check your target environment before relying on it
  • Take advantage of structural patterns (matching list/dict shapes) for parsing commands or structured data, not just simple value equality

At a glance

Purpose
Scripting and general-purpose applications
File extension
.py
Runs in
Python interpreter
Usually used with
Python standard library and packages

Specifications & further reading

Related Python documentation

if
The if statement is Python's primary conditional control structure. It allows your program to make decisions by executing different code blocks based on whether a condition is True or False. The if statement is fundamental to creating dynamic, responsive programs that can adapt their behavior based on various conditions, user input, or data states.
for
The for loop in Python is used to iterate over sequences like lists, tuples, strings, or any iterable object. Unlike traditional for loops in other languages that use counters, Python's for loop is more like a "for each" loop, automatically handling the iteration details. It's one of the most commonly used constructs in Python for processing collections and repeating actions.
while
The while loop repeats a block of code as long as its condition remains True. Unlike a for loop, which iterates a known number of times over a sequence, a while loop is ideal when you don't know in advance how many iterations you'll need - like waiting for valid user input or running until some external condition changes. A while loop can also have an optional else clause that runs if the loop finishes normally, without hitting a break.
break and continue
break and continue give you fine-grained control over loop execution. break immediately exits the nearest enclosing loop entirely, skipping any remaining iterations. continue skips just the rest of the current iteration and jumps straight to the next one, without exiting the loop. Both work inside for and while loops.