Created
June 18, 2014 12:12
-
-
Save mooware/27ba587c7a66f6b566d6 to your computer and use it in GitHub Desktop.
Toying around with metaprogramming in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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