diff --git a/toolz/curried/__init__.py b/toolz/curried/__init__.py index 43aeffd4..fab6255f 100644 --- a/toolz/curried/__init__.py +++ b/toolz/curried/__init__.py @@ -26,6 +26,7 @@ import toolz from . import operator from toolz import ( + apply, comp, complement, compose, diff --git a/toolz/functoolz.py b/toolz/functoolz.py index 238d1b16..be6fa204 100644 --- a/toolz/functoolz.py +++ b/toolz/functoolz.py @@ -8,8 +8,9 @@ from .utils import no_default -__all__ = ('identity', 'thread_first', 'thread_last', 'memoize', 'compose', - 'pipe', 'complement', 'juxt', 'do', 'curry', 'flip', 'excepts') +__all__ = ('identity', 'apply', 'thread_first', 'thread_last', 'memoize', + 'compose', 'pipe', 'complement', 'juxt', 'do', 'curry', 'flip', + 'excepts') def identity(x): @@ -21,6 +22,22 @@ def identity(x): return x +def apply(*func_and_args, **kwargs): + """ Applies a function and returns the results + >>> def double(x): return 2*x + >>> def inc(x): return x + 1 + >>> apply(double, 5) + 10 + + >>> tuple(map(apply, [double, inc, double], [10, 500, 8000])) + (20, 501, 16000) + """ + if not func_and_args: + raise TypeError('func argument is required') + func, args = func_and_args[0], func_and_args[1:] + return func(*args, **kwargs) + + def thread_first(val, *forms): """ Thread value through a sequence of functions/forms diff --git a/toolz/tests/test_functoolz.py b/toolz/tests/test_functoolz.py index deda6068..dcb43af1 100644 --- a/toolz/tests/test_functoolz.py +++ b/toolz/tests/test_functoolz.py @@ -1,7 +1,7 @@ import platform from toolz.functoolz import (thread_first, thread_last, memoize, curry, - compose, pipe, complement, do, juxt, flip, excepts) + compose, pipe, complement, do, juxt, flip, excepts, apply) from operator import add, mul, itemgetter from toolz.utils import raises from functools import partial @@ -23,6 +23,12 @@ def double(x): return 2 * x +def test_apply(): + assert apply(double, 5) == 10 + assert tuple(map(apply, [double, inc, double], [10, 500, 8000])) == (20, 501, 16000) + assert raises(TypeError, apply) + + def test_thread_first(): assert thread_first(2) == 2 assert thread_first(2, inc) == 3