brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's match statement picks apart lists and values by their shape

Python
~/tips/tip-python-match-statement-structural-pattern-matching

match cmd.split():

match and case unpack sequences by shape, with guards and alternatives, from Python 3.10.

match looks like a nicer elif chain, but it is better at taking a list apart by shape. It needs Python 3.10 or newer.

def handle(cmd):
    match cmd.split():
        case ["go", direction]:
            return f"going {direction}"
        case ["take", *items] if items:
            return f"taking {', '.join(items)}"
        case ["quit" | "exit"]:
            return "bye"
        case _:
            return "huh?"

for c in ["go north", "take lamp key", "exit", "dance", "take"]:
    print(c, "->", handle(c))

Output:

go north -> going north
take lamp key -> taking lamp, key
exit -> bye
dance -> huh?
take -> huh?

A pattern binds names (direction, items), *items grabs the rest, | offers alternatives, and if adds a guard. A bare take fell through to _ because the guard needs at least one item.

The caveat: a bare name in a pattern is a capture, not a comparison. If you write case RED: with a constant called RED, it matches anything. Python catches the worst case, since a later case _ then fails with SyntaxError: name capture 'RED' makes remaining patterns unreachable. Use a dotted name such as Color.RED to compare against a constant.

Further reading: The match statement, PEP 636 – Structural Pattern Matching: Tutorial

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link