Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
curryable functions in python - no kwargs yet
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)
Owner

thomasballinger commented Mar 4, 2013

Should write this in Python 3.3 so signatures can be dynamically set

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