Pattern matching

suggest change

Introduced in Python 3.10 (via PEP 634, PEP 635, and PEP 636), Structural Pattern Matching provides the match / case statement. Far more powerful than traditional switch/case statements found in C, Java, or JavaScript, Python's structural pattern matching compares both the value and the shape/structure of data, automatically destructuring sequences, mappings, and class objects into local variables.


1. Basic Syntax and Literal Patterns

The simplest form of pattern matching compares a subject expression against literal values:

def http_status(code: int) -> str:
    match code:
        case 200:
            return "OK"
        case 201:
            return "Created"
        case 400:
            return "Bad Request"
        case 401 | 403:  # Combine multiple alternatives using '|'
            return "Unauthorized or Forbidden"
        case 404:
            return "Not Found"
        case 500:
            return "Internal Server Error"
        case _:  # Wildcard pattern matches anything (like 'default' or 'else')
            return f"Unknown status code ({code})"

print(http_status(200))  # Output: OK
print(http_status(403))  # Output: Unauthorized or Forbidden
print(http_status(418))  # Output: Unknown status code (418)

2. Sequence Patterns and Destructuring

You can match and unpack sequences (lists or tuples) by length and structure:

def process_command(command: list[str]) -> None:
    match command:
        case ["quit"]:
            print("Exiting application...")
        case ["load", filename]:
            print(f"Loading file from: {filename}")
        case ["move", ("up" | "down" | "left" | "right") as direction, steps]:
            print(f"Moving {steps} step(s) {direction}")
        case ["concat", *items]:  # Starred unpacking for variable lengths
            print(f"Concatenating {len(items)} items: {', '.join(items)}")
        case _:
            print(f"Unrecognized command: {command}")

process_command(["load", "data.csv"])
# Output: Loading file from: data.csv

process_command(["move", "up", "5"])
# Output: Moving 5 step(s) up

process_command(["concat", "hello", "world", "!"])
# Output: Concatenating 3 items: hello, world, !

3. Mapping Patterns (Dictionaries)

Mapping patterns verify that a dictionary contains specific keys and binds their values. Extra keys in the dictionary are ignored by default:

def handle_event(event: dict) -> None:
    match event:
        case {"type": "click", "x": x, "y": y}:
            print(f"Mouse clicked at position ({x}, {y})")
        case {"type": "keypress", "key": ("Enter" | "Return")}:
            print("Submission triggered via Enter key")
        case {"type": "keypress", "key": key}:
            print(f"Key pressed: {key}")
        case {"type": "error", "message": msg, **extra}:
            print(f"Error: {msg} (Extra metadata: {extra})")
        case _:
            print("Unhandled event payload")

handle_event({"type": "click", "x": 100, "y": 250, "timestamp": 123456})
# Output: Mouse clicked at position (100, 250)

4. Class and Object Patterns

Pattern matching works seamlessly with custom classes and dataclasses. You can inspect object types and extract attributes:

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

@dataclass
class Circle:
    center: Point
    radius: float

@dataclass
class Rectangle:
    top_left: Point
    width: float
    height: float

def describe_shape(shape) -> str:
    match shape:
        case Point(x=0, y=0):
            return "Origin point (0, 0)"
        case Point(x=x, y=y):
            return f"Point at ({x}, {y})"
        case Circle(center=Point(x=0, y=0), radius=r):
            return f"Circle centered at origin with radius {r}"
        case Circle(center=Point(x=cx, y=cy), radius=r):
            return f"Circle at ({cx}, {cy}) with radius {r}"
        case Rectangle(top_left=Point(x, y), width=w, height=h):
            return f"Rectangle at ({x}, {y}) sized {w}x{h}"
        case _:
            return "Unknown shape"

p = Point(0, 0)
c = Circle(Point(10, 20), 5)
print(describe_shape(p)) # Output: Origin point (0, 0)
print(describe_shape(c)) # Output: Circle at (10, 20) with radius 5

Positional Matching with __match_args__

By default, standard classes require keyword arguments in patterns (Point(x=1, y=2)). Dataclasses automatically define __match_args__, allowing positional arguments. For ordinary classes, define __match_args__ explicitly:

class Vector:
    __match_args__ = ("x", "y")

    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y

# Now positional matching works:
# case Vector(0, y): ...

5. Guards (if Clauses)

A pattern can include an optional if condition called a guard. The case only matches if the structural pattern matches and the guard evaluates to true:

def classify_point(point: Point) -> str:
    match point:
        case Point(x, y) if x == y:
            return f"Point lies on diagonal line y=x at {x}"
        case Point(x, y) if x == -y:
            return f"Point lies on anti-diagonal line y=-x at {x}"
        case Point(x, y):
            return f"General point at ({x}, {y})"

print(classify_point(Point(5, 5)))   # Output: Point lies on diagonal line y=x at 5
print(classify_point(Point(3, -3)))  # Output: Point lies on anti-diagonal line y=-x at 3

6. Important Pitfall: Variable Binding vs. Equality

In Python pattern matching, a bare name in a case clause is always treated as a variable capture, not an equality check against an existing variable in outer scope:

STATUS_OK = 200
status = 404

match status:
    # BUG: This does NOT check if status == STATUS_OK.
    # Instead, it creates a new local variable named STATUS_OK and binds 404 to it!
    case STATUS_OK:
        print("This branch will ALWAYS execute!")

To compare against an existing variable or constant, use a dotted name (attribute access) or an Enum:

from enum import Enum

class Status(Enum):
    OK = 200
    NOT_FOUND = 404

current_status = Status.NOT_FOUND

match current_status:
    case Status.OK:
        print("Success")
    case Status.NOT_FOUND:  # Correctly matched using dotted attribute access
        print("Resource not found")

Best Practices

  1. Use Guards Sparingly: Keep patterns structural; avoid complex business logic inside if guards.
  2. Always Provide a Wildcard Fallback: Include case _: when exhaustive pattern coverage is not guaranteed to prevent silent unhandled values.
  3. Prefer Dataclasses for Complex Payloads: Dataclasses automatically provide __match_args__, making object pattern matching concise and readable.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents