Skip to content

Instantly share code, notes, and snippets.

@thomasballinger
Last active December 14, 2015 10:08
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 thomasballinger/5069378 to your computer and use it in GitHub Desktop.
Save thomasballinger/5069378 to your computer and use it in GitHub Desktop.
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)
@thomasballinger
Copy link
Author

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