Skip to content

Instantly share code, notes, and snippets.

@rossdylan
Created August 7, 2012 16:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rossdylan/3287138 to your computer and use it in GitHub Desktop.
Save rossdylan/3287138 to your computer and use it in GitHub Desktop.
Function composition in python
from functools import partial
def _composed(f, g, *args, **kwargs):
return f(g(*args, **kwargs))
def compose(*a):
try:
return partial(_composed, a[0], compose(*a[1:]))
except:
return a[0]
@piotrklibert
Copy link

There is a very old, but still relevant (despite the additions to stdlib in later times, like partial) functional.py module (I can't find it's homepage, maybe it expired, its still in cheeseshop though) which I use. It's compose function looks like this:

def compose(func_1, func_2):
    """
    compose(func_1, func_2) -> function

    The function returned by compose is a composition of func_1 and func_2.
    That is, compose(func_1, func_2)(5) == func_1(func_2(5))
    """
    if not callable(func_1):
        raise TypeError("First argument to compose must be callable")
    if not callable(func_2):
        raise TypeError("Second argument to compose must be callable")

    def composition(*args, **kwargs):
        return func_1(func_2(*args, **kwargs))
    return composition

One can define multicompose in terms of fold and compose:

multicompose = lambda *funs: reduce(compose, funs)

@jgomo3
Copy link

jgomo3 commented Feb 4, 2016

Relevant: https://mathieularose.com/function-composition-in-python/

A comment from Fred Loney, gives an elegant solution:

def compose(*funcs):
    return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment