Skip to main content

Pattern matching in Python

Project description

https://img.shields.io/circleci/project/github/brettbeatty/hand_grenade.svg https://img.shields.io/github/license/brettbeatty/hand_grenade.svg https://img.shields.io/codecov/c/github/brettbeatty/hand_grenade.svg https://img.shields.io/pypi/v/hand_grenade.svg

Matchstick provides a decorator that allows for the overloading of Python functions.

>>> from matchstick import when
>>> @when('x >= 0')
... def f(x):
...     return x
...
>>> @when('x < 0')
... def f(x):
...     return -x
...
>>> f(3)
3
>>> f(-2)
2
>>> f('a')
'a'

Basic Use

Conditions

The match decorator takes a condition as a string. When the decorated function gets called, overloaded functions (grouped by module and qualified name) are checked in the order they are defined. Each condition is evaluated with the arguments passed to the function (including default parameter values, where applicable). If the condition evaluates truthy, the corresponding function is called. If the condition evaluates falsy or raises an exception, the corresponding function is passed over.

>>> @when('x[2] == 5')
... def f(x):
...     return sum(x)
...
>>> @when('len(x) > 3')
... def f(x):
...     return x[3:]
...
>>> @when('True')
... def f(x):
...     return x
...
>>> f([3, 4, 5, 6])
18
>>> f([0, 1, 2, 3])
[3]
>>> f('abcd')
'd'
>>> f({})
{}

NoMatchException

If none of the conditions for a function evaluate truthy, a matchstick.NoMatchException is raised.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for matchstick, version 0.1.1
Filename, size File type Python version Upload date Hashes
Filename, size matchstick-0.1.1.tar.gz (3.8 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page