Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard Python wrapper to turn f(x) into f(*x)?

I keep coming across use cases for the following wrapper:

def asterisk(fn):
   def retfn(x):
      return fn(*x)
   return retfn

Is there something in the standard Python 2 library that already does this? I had a look in functools, but couldn't find anything.

For context, here is a recent use case:

print map(asterisk(operator.sub), [[-20, 20], [-20, 20], [32, 32]])
like image 962
NPE Avatar asked Aug 22 '26 18:08

NPE


2 Answers

To provide this:

print map(asterisk(operator.sub), [[-20, 20], [-20, 20], [32, 32]])

You should use

from itertools import starmap
print starmap(operator.sub, [[-20, 20], [-20, 20], [32, 32]])

P.S. As far as I know, there is no built-in functions for such functionality in Python. Some time ago, I talked in Python mailing list about lack of "apply" functionality, which is more "general" questions. I think, something like operator.apply(f, args) will be good for many cases. This functional representation for function application can also except argument about arguments passing model.

like image 141
Alexey Kachayev Avatar answered Aug 25 '26 09:08

Alexey Kachayev


While starmap is a good solution for some cases, another option here, which I feel is far more readable in this case, is to use a list comprehension instead:

[x - y for x, y in [[-20, 20], [-20, 20], [32, 32]]

I would recommend that you use a list comprehension (or generator expression) as soon as you find yourself using the operator module or lambdas, as it will result in far more readable (and often faster) code.

like image 40
Gareth Latty Avatar answered Aug 25 '26 08:08

Gareth Latty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!