Apply list of functions on an object in Python
I think this should fit your 'functional' criteria, To answer your question, I don't think there is a clean way and you should just acclimatize to list comprehensions.
As suggested by @J.F.Sebastian
>>> from operator import methodcaller
>>> funcs = (lambda x: x + 1, lambda x: x + 2)
>>> obj = 5
>>> list(map(methodcaller('__call__', obj), funcs))
[6, 7]
Here is a crazy way of doing it:
>>> from itertools import starmap, repeat
>>> from types import FunctionType
>>> funcs = (lambda x: x + 1, lambda x: x + 2)
>>> obj = 5
>>> list(starmap(FunctionType.__call__, zip(funcs, repeat(obj))))
[6, 7]
As suggested by @AleksiTorhamo
>>> from itertools import repeat
>>> from types import FunctionType
>>> obj = 5
>>> funcs = (lambda x: x + 1, lambda x: x + 2)
>>> list(map(FunctionType.__call__, funcs, repeat(obj)))
[6, 7]
The problem is the missing $
operator which is trivially defined by
def apply(f, a):
return f(a)
then one can do the currying ($ obj)
with a partial in python like this: partial(apply, a=obj)
having this we can do a map apply with
map(partial(apply, a=obj), [foo1, foo2]))
You could always just create a function to take care of it for you:
def map_funcs(obj, func_list):
return [func(obj) for func in func_list]
# I was under the impression that the OP wanted to compose the functions,
# i.e. f3(f2(f1(f0(obj))), for which the line below is applicable:
# return reduce(lambda o, func: func(o), func_list, obj)
map_funcs(it, [Buy, Use, Break, Fix])