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 functoolz.reorder_args #546

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions toolz/curried/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
reduce = toolz.curry(toolz.reduce)
reduceby = toolz.curry(toolz.reduceby)
remove = toolz.curry(toolz.remove)
reorder_args = toolz.curry(toolz.reorder_args)
sliding_window = toolz.curry(toolz.sliding_window)
sorted = toolz.curry(toolz.sorted)
tail = toolz.curry(toolz.tail)
Expand Down
42 changes: 39 additions & 3 deletions toolz/functoolz.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from functools import reduce, partial
from functools import reduce, partial, wraps
import inspect
import sys
from operator import attrgetter, not_
from operator import itemgetter, attrgetter, not_
from importlib import import_module
from types import MethodType

Expand All @@ -12,7 +12,7 @@

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

PYPY = hasattr(sys, 'pypy_version_info')

Expand Down Expand Up @@ -731,6 +731,42 @@ def flip(func, a, b):
return func(b, a)


def reorder_args(func, new_args):
""" Returns a new function with a desired argument order.

>>> def op(a, b, c):
... return a // (b - c)
...
>>> new_op = reorder_args(op, ('c', 'a', 'b'))
>>> new_op(1, 2, 3) == op(2, 3, 1)
True
"""
func_sig = inspect.signature(func)
arg_map = []
parameters = [None] * len(func_sig.parameters)
for i, arg in enumerate(func_sig.parameters.values()):
if (arg.kind in {inspect.Parameter.POSITIONAL_ONLY,
inspect.Parameter.VAR_POSITIONAL,
inspect.Parameter.POSITIONAL_OR_KEYWORD}
and arg.default is inspect._empty):
try:
new_ind = new_args.index(arg.name)
arg_map.append(new_ind)
parameters[new_ind] = arg
except ValueError:
raise ValueError(f"Unable to find positional argument `{arg.name}` in signature for `{func.__name__}`")
else:
parameters[i] = arg

_mapper = itemgetter(*arg_map)
@wraps(func)
def wrapper(*args, **kwargs):
return func(*_mapper(args), **kwargs)

wrapper.__signature__ = func_sig.replace(parameters=parameters)
return wrapper


def return_none(exc):
""" Returns None.
"""
Expand Down
18 changes: 16 additions & 2 deletions toolz/tests/test_functoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
import toolz
from toolz.functoolz import (thread_first, thread_last, memoize, curry,
compose, compose_left, pipe, complement, do, juxt,
flip, excepts, apply)
from operator import add, mul, itemgetter
flip, excepts, apply, reorder_args)
from operator import add, mul, getitem, itemgetter
from toolz.utils import raises
from functools import partial

Expand Down Expand Up @@ -794,3 +794,17 @@ def raise_(a):
excepting = excepts(object(), object(), object())
assert excepting.__name__ == 'excepting'
assert excepting.__doc__ == excepts.__doc__


def test_reorder_args():
def op(a, b, c, d=1):
return a // (b - c) + d

new_op = reorder_args(op, ('c', 'a', 'b'))
assert new_op(1, 2, 3, d=1) == op(2, 3, 1, d=1)

# test builtin functions (ie C functions)
getflip = reorder_args(getitem, ('b', 'a'))
get1 = curry(getflip, 1)
assert get1([1, 2, 3, 1, 1]) == 2