import toolz
toolz
Lightning Talk¶toolz
?¶[A] set of utility functions for iterators, functions, and dictionaries. - toolz docs
toolz
extends the Python standard libraries functools
and itertools
. It includes many functions that should be part of the standard library (e.g. groupby
, compose
) and some extras.
It keeps things simple and doesn't try to be creative. Every thing is implemented in a pythonic way (no special syntax or hacks). Mostly sticks to functions that are in the Clojure standard library.
Everything in toolz
is easily serializable, which helps make parallel programing easier.
Was created by Matthew Rocklin and has a decent number of contributors (~31). There is also a cythonized version called cytoolz
.
tack_on = toolz.compose(lambda txt: txt + "_3",
lambda txt: txt + "_2",
lambda txt: txt + "_1",
lambda txt: txt + "_0")
tack_on("foo")
'foo_0_1_2_3'
@toolz.curry
def tack_on_single(ext, txt):
return txt + ext
tack_on_composed = toolz.compose(tack_on_single("_3"),
tack_on_single("_2"),
tack_on_single("_1"),
tack_on_single("_0"))
tack_on_composed("foo")
'foo_0_1_2_3'
is_even = lambda n: bool(n % 2)
toolz.groupby(is_even, range(20))
{False: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18], True: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]}
toolz.groupby(len, ["Larry", "Moe", "Curly", "Shemp",
"spam", "eggs",
"and", "other", "stuff"])
{3: ['Moe', 'and'], 4: ['spam', 'eggs'], 5: ['Larry', 'Curly', 'Shemp', 'other', 'stuff']}
groupby
¶lower_first = toolz.compose(toolz.first, str.lower)
toolz.groupby(lower_first, ["Larry", "Moe", "Curly", "Shemp",
"spam", "eggs",
"and", "other", "stuff"])
{'a': ['and'], 'c': ['Curly'], 'e': ['eggs'], 'l': ['Larry'], 'm': ['Moe'], 'o': ['other'], 's': ['Shemp', 'spam', 'stuff']}
tlz.pipe(1,
lambda n: n + 1,
lambda n: n * 2,
lambda n: n / 2,
lambda n: n - 1)
1
tlz.pipe("foo",
tack_on_single("_0"),
tack_on_single("_1"),
tack_on_single("_2"),
tack_on_single("_3"))
'foo_0_1_2_3'