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.

Source Distribution

matchstick-0.1.1.tar.gz (3.8 kB view details)

Uploaded Source

File details

Details for the file matchstick-0.1.1.tar.gz.

File metadata

  • Download URL: matchstick-0.1.1.tar.gz
  • Upload date:
  • Size: 3.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for matchstick-0.1.1.tar.gz
Algorithm Hash digest
SHA256 16f114c166569b85f8819ae6e8daf73e8469865760c86d45fb2ad5dae12be008
MD5 472c19c785f23c82e66f5942d7ffda23
BLAKE2b-256 a7c1203df211fb6334a02536bd1b521c45af5b5564dcf40b766a84b7e39fee91

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page