Search code examples
pythonfunctional-programming

Apply list of functions on an object in Python


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?


Solution

  • 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]