I am trying to write a currying decorator in python, and I think I've got the general idea down, but still got some cases that aren't working right...
def curry(fun):
cache = []
numargs = fun.func_code.co_argcount
def new_fun(*args, **kwargs):
print args
print kwargs
cache.extend(list(args))
if len(cache) >= numargs: # easier to do it explicitly than with exceptions
temp = []
for _ in xrange(numargs):
temp.append(cache.pop())
fun(*temp)
return new_fun
@curry
def myfun(a,b):
print a,b
While for the following case this works fine:
myfun(5)
myfun(5)
For the following case it fails:
myfun(6)(7)
Any pointers on how to correctly do this would be greatly appreciated!
Thanks!
The below implementation is naive, google for "currying python" for more accurate examples.
As it's cool to write currying decorators in python, I tried mine: 5 lines of code, readable, and tested curry function.
The solution from Roger Christman will not work with every constellation. I applied a small fix to also handle this situation:
The small fix that makes it work with every constellation lies in the returned lambda:
This one is fairly simple and doesn't use inspect or examine the given function's args
I think I've got a better one:
This solution uses Python's own
functools.partial
function instead of effectively recreating that functionality. It also allows you to pass in more arguments than the minimum, -allows keyword arguments,- and just passes through functions that don't have to take arguments, since those are pointless to curry. (Granted, the programmer should know better than to curry zero-arity or multi-arity functions, but it's better than creating a new function in that case.)UPDATE: Whoops, the keyword argument part doesn't actually work right. Also, optional arguments are counted in the arity but *args are not. Weird.
Simplest way to curry a function in python is like this:
https://gist.github.com/hkupty/0ba733c0374964d41dec
One can use it as follows:
which will produce: