Pythonic function composition

Lonnie Princehouse finite.automaton at gmail.com
Mon Oct 25 16:13:30 EDT 2004


How about some recursion?

def compose(f, *fns):
    if not fns:
        return f
    else:
        return lambda x: f(compose(*fns)(x))

...

>>> from math import *
>>> foo = compose(sin, sqrt, abs)   # sin(sqrt(abs(x)))
>>> foo(-((pi/2.)**2))
1.0

...or you could try it this way, which makes some assumptions about
function names, but will possibly run faster:

def compose(*fns):
    fnames = [f.__name__ for f in fns]
    expr = "%s(x%s" % ('('.join(fnames),')'*len(fns))
    return eval("lambda x: %s" % expr)



More information about the Python-list mailing list