简体   繁体   中英

Apply multiple functions to the same argument in functional Python

I am trying to "invert" map (same function, multiple arguments) in a case where I have multiple function that I want to apply to the same argument. I am trying to find a more function approach to replace the classical

arg = "My fixed argument"
list_of_functions = [f, g, h] #note that they all have the same signature
[fun(arg) for fun in list_of_functions]

The only thing I could come up with is

map(lambda x: x(arg), list_of_functions)

which is not really great.

You can try:

from operator import methodcaller

map(methodcaller('__call__', arg), list_of_functions)

The operator module also has similar functions for getting fixed attributes or items out of an object, often useful in functional-esque programming style. Nothing directly for calling a callable, but methodcaller is close enough.

Though, I personally like list comprehension more in this case. Maybe if there was a direct equivalent in the operator module, like:

def functioncaller(*args, **kwargs):
    return lambda fun:fun(*args, **kwargs)

…to use it as:

map(functioncaller(arg), list_of_functions)

…then maybe it would be convenient enough?

在Python 3中,您的map()示例返回一个map对象,因此仅在对其进行迭代时才调用函数,这至少是惰性的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM