Alakazam
Alakazam is an open-source Python library which adds convenient syntax for functional programming stream operations to Python.
Python already supports the basic operations needed to perform
functional-style streaming operations: those being map
,
filter
, and functools.reduce
. However,
these operations have the unfortunate side effect of being written
in the opposite than one would read the code. Consider
the following snippet.
list(filter(lambda x: x: x % 2 == 0, map(lambda x: x ** 2, arr)))
The logic of this code is as follows. Take an input list arr
,
square each element, and then keep only the even values, producing
a new list as output. But the code reads in reverse:
produce a list, which is the result of filtering to keep only the
even values, from the result of squaring each element of the input list arr
Alakazam introduces a new datatype, appropriately called Alakazam
,
which defines map
and filter
as instance
methods that can be called in a more OOP-style. The above code
snippet, in Alakazam, is as follows.
import alakazam as zz
zz.of(arr).map(lambda x: x ** 2).filter(lambda x: x % 2 == 0).list()
In fact, Alakazam pretties up the Python lambda
syntax
as well. For lambdas that only use Python operators, such as the
modulo, equals sign, and exponentiation operators in this example,
we can use a Boost-style syntax to build the lambda, rather than
having to write it out explicitly.
import alakazam as zz
from alakazam import _1
zz.of(arr).map(_1 ** 2).filter(_1 % 2 == 0).list()
The Alakazam
class provides over 70 helper methods,
adapting all of Python's built-in streaming functions, as well as
all of itertools
. Alakazam smooths out some of the
corner cases of these functions and additionally provides some
useful list streaming operations from Haskell that are not native
to Python.
Alakazam can be installed with pip
. It works on all
versions of Python 3, as well as Python 2.6 and newer, and it has
no additional dependencies.