Вопрос

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.

It's not really necessary, because for any callable f, you can write:

lambda *args: f(*args)

Which does what you need. The syntax is shorter than any library call. It's only if you need to reify the transformation itself that you need that, but then writing that is as simple as writing:

def starify(f):
    return lambda *args: f(*args)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top