Apply multiple functions to the same argument in functional Python

旧时模样 提交于 2020-01-13 07:01:12

问题


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.


回答1:


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?




回答2:


In Python 3 your map() example returns a map object, so the functions are only called when it is iterated over, which is at least lazy.



来源:https://stackoverflow.com/questions/33659139/apply-multiple-functions-to-the-same-argument-in-functional-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!