Last active
December 14, 2015 10:08
-
-
Save thomasballinger/5069378 to your computer and use it in GitHub Desktop.
curryable functions in python - no kwargs yet
This file contains hidden or 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
import inspect | |
from functools import partial | |
def curryable(func): | |
spec = inspect.getargspec(func) | |
nargs = len(spec.args) | |
if spec.varargs: | |
raise ValueError('Hard to make a multiarity function curryable') | |
if spec.defaults: | |
raise ValueError('Hard to make a function with default arguments curryable') | |
#TODO try to keep kwargs working | |
def curryable_function(local_func, args_left): | |
def new_func(*args): | |
if len(args) > args_left: | |
raise TypeError('func takes %d args at in this form, %d args total' % (args_left, nargs)) | |
elif len(args) == args_left: | |
return local_func(*args) | |
else: | |
return curryable_function(partial(local_func, *args), args_left - len(args)) | |
return new_func | |
return curryable_function(func, nargs) | |
@curryable | |
def foo(x, y, z): | |
return x + y + z | |
print foo(1,2,3) | |
print foo(1)(2)(3) | |
print foo(1, 2)(3) | |
print foo(1)(2, 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should write this in Python 3.3 so signatures can be dynamically set