Skip to content

Commit

Permalink
Merge pull request #251 from llllllllll/flip
Browse files Browse the repository at this point in the history
ENH: Adds flip
  • Loading branch information
mrocklin committed Jul 27, 2015
2 parents 8ff64da + 43d8590 commit 330f827
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
29 changes: 28 additions & 1 deletion toolz/functoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


__all__ = ('identity', 'thread_first', 'thread_last', 'memoize', 'compose',
'pipe', 'complement', 'juxt', 'do', 'curry')
'pipe', 'complement', 'juxt', 'do', 'curry', 'flip')


def identity(x):
Expand Down Expand Up @@ -541,3 +541,30 @@ def do(func, x):
"""
func(x)
return x


@curry
def flip(func, a, b):
"""Call the function call with the arguments flipped.
This function is curried.
>>> def div(a, b):
... return a / b
...
>>> flip(div, 2, 1)
0.5
>>> div_by_two = flip(div, 2)
>>> div_by_two(4)
2.0
This is particularly useful for built in functions and functions defined
in C extensions that accept positional only arguments. For example:
isinstance, issubclass.
>>> data = [1, 'a', 'b', 2, 1.5, object(), 3]
>>> only_ints = list(filter(flip(isinstance, int), data))
>>> only_ints
[1, 2, 3]
"""
return func(b, a)
10 changes: 8 additions & 2 deletions toolz/tests/test_functoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@


from toolz.functoolz import (thread_first, thread_last, memoize, curry,
compose, pipe, complement, do, juxt)
compose, pipe, complement, do, juxt, flip)
from toolz.functoolz import _num_required_args
from operator import add, mul, itemgetter
from toolz.utils import raises
from functools import partial
from toolz.compatibility import reduce, PY3


def iseven(x):
Expand Down Expand Up @@ -502,3 +501,10 @@ def test_juxt_generator_input():
juxtfunc = juxt(itemgetter(2*i) for i in range(5))
assert juxtfunc(data) == (0, 2, 4, 6, 8)
assert juxtfunc(data) == (0, 2, 4, 6, 8)


def test_flip():
def f(a, b):
return a, b

assert flip(f, 'a', 'b') == ('b', 'a')

0 comments on commit 330f827

Please sign in to comment.