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

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading