Composing functions in python

Starless picture Starless · May 24, 2013 · Viewed 33.3k times · Source

I have an array of functions and I'm trying to produce one function which consists of the composition of the elements in my array. My approach is:

def compose(list):
    if len(list) == 1:
        return lambda x:list[0](x)
    list.reverse()
    final=lambda x:x
    for f in list:
        final=lambda x:f(final(x))
    return final

This method doesn't seems to be working, help will be appreciated.

(I'm reversing the list because this is the order of composition I want the functions to be)

Answer

Suor picture Suor · Jun 4, 2014

The easiest approach would be first to write a composition of 2 functions:

def compose2(f, g):
    return lambda *a, **kw: f(g(*a, **kw))

And then use reduce to compose more functions:

def compose(*fs):
    return reduce(compose2, fs)

Or you can use some library, which already contains compose function.