Is there any clean way to apply a list of functions on an object in Python without lambda or list comprehensions? Like the Haskell expression:
map ($ obj) [foo1,foo2]
Example with lambda in Python:
response = map(lambda foo:foo(obj),[foo1,foo2]) #fooX:object->Bool
Is it extendable to class functions?
Perhaps something from operator or itertools?
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])
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]
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