pythonintermediate

Structural Pattern Matching (match/case)

Use Python 3.10+ match/case for expressive pattern matching with guards and destructuring.

python
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

@dataclass
class Circle:
    center: Point
    radius: float

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

def describe_shape(shape):
    match shape:
        case Circle(center=Point(0, 0), radius=r):
            return f"Circle at origin with radius {r}"
        case Circle(radius=r) if r > 100:
            return f"Large circle with radius {r}"
        case Rectangle(width=w, height=h) if w == h:
            return f"Square with side {w}"
        case Rectangle(width=w, height=h):
            return f"Rectangle {w}x{h}"
        case _:
            return "Unknown shape"

# Match on dict structures
def handle_event(event: dict) -> None:
    match event:
        case {"type": "click", "button": "left", "x": x, "y": y}:
            print(f"Left click at ({x}, {y})")
        case {"type": "keypress", "key": str(k)} if len(k) == 1:
            print(f"Character typed: {k}")
        case {"type": t}:
            print(f"Unhandled event: {t}")

# Match on sequences
def parse_command(args: list[str]) -> None:
    match args:
        case ["quit" | "exit"]:
            print("Goodbye!")
        case ["hello", name]:
            print(f"Hello, {name}!")
        case ["add", *items] if items:
            print(f"Adding: {', '.join(items)}")
        case []:
            print("No command")

Use Cases

  • command parsing
  • event handling
  • shape/type dispatch

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.