Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add apply #411

Merged
merged 7 commits into from Jun 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions toolz/curried/__init__.py
Expand Up @@ -26,6 +26,7 @@
import toolz
from . import operator
from toolz import (
apply,
comp,
complement,
compose,
Expand Down
21 changes: 19 additions & 2 deletions toolz/functoolz.py
Expand Up @@ -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):
Expand All @@ -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

Expand Down
8 changes: 7 additions & 1 deletion 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
Expand All @@ -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
Expand Down