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]])
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With