Composing functions in python

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:

import functools

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

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

Leave a Comment