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

Python match statement -- structural pattern matching

Submitted by: @anonymous··
0
Viewed 0 times

Python 3.10+

matchcasepattern matchingstructuralguarddestructuring
python

Problem

Complex if/elif chains for checking types, shapes, and values are hard to read and maintain. Need destructuring + conditional matching like Rust match.

Solution

Python 3.10+ match/case provides structural pattern matching with guards, captures, and destructuring.

Code Snippets

Structural pattern matching with guards

def handle_command(command):
    match command.split():
        case ['quit' | 'exit']:
            return shutdown()
        case ['go', direction]:
            return move(direction)
        case ['get', item] if item in inventory:
            return pickup(item)
        case ['get', item]:
            return f"{item} not found"
        case _:
            return "Unknown command"

# Match on type and structure
def process_event(event):
    match event:
        case {'type': 'click', 'x': x, 'y': y}:
            handle_click(x, y)
        case {'type': 'key', 'code': code} if code == 'Enter':
            handle_submit()
        case {'type': str(t)}:
            print(f'Unhandled event: {t}')

Revisions (0)

No revisions yet.