Claudio github.com

Pampy – pattern matching for Python  ↦

Pampy is pretty small (150 lines), reasonably fast, and often makes your code more readable, and easier to reason about.

Pattern matching is the feature in Elixir that I miss when using other languages, so it’s awesome to see it brought to Python. Here’s an example of Pampy in action as a Lisp calculator (from the readme):

from pampy import match, REST, _

def lisp(exp):
    return match(exp,
        int,                lambda x: x,
        callable,           lambda x: x,
        (callable, REST),   lambda f, rest: f(*map(lisp, rest)),
        tuple,              lambda t: list(map(lisp, t)),
    )

plus = lambda a, b: a + b
minus = lambda a, b: a - b
from functools import reduce

lisp((plus, 1, 2))                 	# => 3
lisp((plus, 1, (minus, 4, 2)))     	# => 3
lisp((reduce, plus, (range, 10)))       # => 45

Discussion

Sign in or join to comment

0:00 / 0:00