From 887e263d846957b145542f25aa12745356d40abb Mon Sep 17 00:00:00 2001 From: Brian Larsen Date: Sat, 27 May 2023 18:00:39 -0500 Subject: [PATCH] Improve flip to accept *args and kwargs --- cytoolz/_signatures.py | 5 +++-- cytoolz/functoolz.pxd | 2 +- cytoolz/functoolz.pyx | 8 ++++++-- cytoolz/tests/test_functoolz.py | 7 +++++++ 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/cytoolz/_signatures.py b/cytoolz/_signatures.py index 8ed7061..c1b9668 100644 --- a/cytoolz/_signatures.py +++ b/cytoolz/_signatures.py @@ -54,9 +54,10 @@ lambda: None, lambda func: None, lambda func, a: None, - lambda func, a, b: None], + lambda func, a, b: None, + lambda func, *args, **kwargs: None], _flip=[ - lambda func, a, b: None], + lambda func, *args, **kwargs: None], identity=[ lambda x: None], juxt=[ diff --git a/cytoolz/functoolz.pxd b/cytoolz/functoolz.pxd index da203c1..4fb5786 100644 --- a/cytoolz/functoolz.pxd +++ b/cytoolz/functoolz.pxd @@ -55,7 +55,7 @@ cdef class juxt: cpdef object do(object func, object x) -cpdef object flip(object func, object a, object b) +cpdef object c_flip(object func, tuple args, dict kwargs) cpdef object return_none(object exc) diff --git a/cytoolz/functoolz.pyx b/cytoolz/functoolz.pyx index 8a9a2f3..f33d784 100644 --- a/cytoolz/functoolz.pyx +++ b/cytoolz/functoolz.pyx @@ -751,7 +751,11 @@ cpdef object do(object func, object x): return x -cpdef object flip(object func, object a, object b): +cpdef object c_flip(object func, tuple args, dict kwargs): + return PyObject_Call(func, tuple(reversed(args)), kwargs) + + +def flip(func, *args, **kwargs): """ Call the function call with the arguments flipped @@ -775,7 +779,7 @@ cpdef object flip(object func, object a, object b): >>> only_ints [1, 2, 3] """ - return PyObject_CallObject(func, (b, a)) + return c_flip(func, args, kwargs) _flip = flip # uncurried diff --git a/cytoolz/tests/test_functoolz.py b/cytoolz/tests/test_functoolz.py index 47484f6..410e047 100644 --- a/cytoolz/tests/test_functoolz.py +++ b/cytoolz/tests/test_functoolz.py @@ -735,6 +735,13 @@ def f(a, b): assert flip(f, 'a', 'b') == ('b', 'a') +def test_flip_args_kwargs(): + def g(a, b, c, *, d, e): + return a, b, c, d, e + + assert flip(g, 3, 2, 1, d=4, e=5) == (1, 2, 3, 4, 5) + + def test_excepts(): # These are descriptors, make sure this works correctly. assert excepts.__name__ == 'excepts'