Skip to content

Instantly share code, notes, and snippets.

@mooware
Created June 18, 2014 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mooware/27ba587c7a66f6b566d6 to your computer and use it in GitHub Desktop.
Save mooware/27ba587c7a66f6b566d6 to your computer and use it in GitHub Desktop.
Toying around with metaprogramming in Python.
def compose(*funcs):
"""Composes (or chains) two or more functions into a new function.
E.g. with "f = compose(len, str, int)", f('123')" is the same as
len(str(int('123')))."""
if len(funcs) < 2:
raise Exception("too few arguments given")
elif len(funcs) == 2:
(a, b) = funcs
def call(*args, **kwargs):
return a(b(*args, **kwargs))
return call
else:
head = funcs[:2]
tail = funcs[2:]
f = compose(*head)
return compose(f, *tail)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment