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

Python match statement (structural pattern matching)

Submitted by: @anonymous··
0
Viewed 0 times

Python 3.10+

matchcasepattern-matchingstructuralguarddestructure

Problem

Complex if/elif chains for checking object types, structure, and values are verbose and error-prone.

Solution

Use match/case for structural pattern matching (Python 3.10+):

def handle_command(command):
match command.split():
case ['quit']:
return 'Goodbye'
case ['go', direction]:
return f'Going {direction}'
case ['get', item] if item != 'sword':
return f'Picked up {item}'
case ['get', 'sword']:
return 'The sword is too heavy'
case _:
return f'Unknown command: {command}'

# Match on type and structure:
def process(event):
match event:
case {'type': 'click', 'x': x, 'y': y}:
handle_click(x, y)
case {'type': 'key', 'key': 'Enter'}:
handle_enter()
case {'type': str() as t}:
print(f'Unknown event type: {t}')

# Match on class instances:
from dataclasses import dataclass

@dataclass
class Point:
x: float
y: float

match point:
case Point(x=0, y=0):
print('Origin')
case Point(x=0, y=y):
print(f'Y axis at {y}')
case Point(x=x, y=0):
print(f'X axis at {x}')
case Point(x, y) if x == y:
print(f'Diagonal at {x}')
case Point(x, y):
print(f'Point({x}, {y})')

Why

match/case is more readable than if/elif chains for complex dispatch, and the compiler can verify patterns and bindings.

Revisions (0)

No revisions yet.