Skip to main content
Donate to the Python Software Foundation or Purchase a PyCharm License to Benefit the PSF! Donate Now

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.

Filename, size & hash SHA256 hash help File type Python version Upload date
matchstick-0.1.1.tar.gz (3.8 kB) Copy SHA256 hash SHA256 Source None

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page