Skip to main content

Infix operators for Python

Project description

Easily make named infix binary operators in Python.

Demo time:

# the only useful function in the module
>>> from betwixt import infix_operator

# any function of 2 arguments would do
>>> from fnmatch import fnmatch

# make the binary function into an operator, delimited by `*`
>>> matches = infix_operator('*', fnmatch)

# use it
>>> 'foo.txt' *matches* '*.txt'
True

# other delimiters can be used
>>> matches = infix_operator('|', fnmatch)
>>> 'foo.txt' |matches| '*.txt'
True

A decorator form can also be used:

>>> @infix_operator('|')
... def contains(left, right):
...   return right in left

>>> [1, 2, 3] |contains| 1
True

>>> [1, 2, 3] |contains| 0
False

Finally, betwixt is provided as a shorter (and, perhaps, more expressive) alias to infix_operator:

>>> from betwixt import betwixt

>>> @betwixt('*')
... def joining(left, right):
...   return left.join(right)

>>> '_' *joining* ['a', 'b', 'c']
'a_b_c'

>>> split_at = betwixt('//', lambda lhs, rhs: lhs.split(rhs))

>>> 'a_b_c' //split_at// '_'
['a', 'b', 'c']

All these example operators and a few more are available in module betwixt.examples.

The idea was taken from http://code.activestate.com/recipes/384122-infix-operators/ and by a similar C++ hack whose code on the web I cannot find any more, but no actual code has been stolen.

Installation

pip install betwixt

Development

To run the all tests run:

tox

Note, to combine the coverage data from all the tox environments run:

Windows
set PYTEST_ADDOPTS=--cov-append
tox
Other
PYTEST_ADDOPTS=--cov-append tox

Changelog

1.0.0 (2019-01-31)

  • First release on PyPI.

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 betwixt, version 1.0.0
Filename, size File type Python version Upload date Hashes
Filename, size betwixt-1.0.0-py2.py3-none-any.whl (8.9 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size betwixt-1.0.0.tar.gz (21.2 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page