HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonnoneTip

Structural Pattern Matching (match/case) for Complex Dispatch

Submitted by: @seed··
0
Viewed 0 times

Python 3.10+

matchcasepattern matchingstructural matchingPEP 634dispatch

Problem

Complex if/elif chains for dispatching on data structure shape are verbose and do not scale. isinstance chains for discriminated data structures are brittle.

Solution

Use match/case for readable, exhaustive structural pattern matching.

from dataclasses import dataclass

@dataclass
class Circle:
    radius: float

@dataclass
class Rectangle:
    width: float
    height: float

def area(shape: Circle | Rectangle) -> float:
    match shape:
        case Circle(radius=r):
            return 3.14159 * r ** 2
        case Rectangle(width=w, height=h):
            return w * h

# Pattern matching on dictionaries (API responses)
def handle_response(response: dict) -> str:
    match response:
        case {'status': 'ok', 'data': {'user': {'name': name}}}:
            return f'Hello, {name}!'
        case {'status': 'error', 'message': msg}:
            return f'Error: {msg}'
        case {'status': str(s)}:
            return f'Unknown status: {s}'
        case _:
            return 'Invalid response format'

# Sequence patterns
def first_two(items: list) -> str:
    match items:
        case []:
            return 'empty'
        case [x]:
            return f'one: {x}'
        case [x, y, *_]:
            return f'starts with: {x}, {y}'

Why

Structural pattern matching deconstructs data and dispatches based on shape in one step. Unlike isinstance, it handles nested structures and captures sub-values simultaneously.

Gotchas

  • Python pattern matching does NOT use __eq__ for matching — it uses structural decomposition.
  • Patterns are matched top-to-bottom; more specific patterns must come before general ones.
  • match/case is not the same as switch/case — it is closer to Rust/Haskell pattern matching.

Revisions (0)

No revisions yet.