Thursday, April 19, 2012

Python - Somthing similar to curry

Currying is a pretty neat idea. However python has its own partial in functools module.

So, left with nothing better to do, I had an idea of a function that waits till it has been called with the required number of arguments to return the result. That is, the arguments from the previous calls should be saved somewhere and used later.

So, here is the result almost_curry!


class almost_curry():
    def __init__(self,func):
        import inspect as insp
        self.func = func
        self.argsInFunc = insp.getargspec(func)[0]
        self.argsReq = len(self.argsInFunc)
        self.args = []
        self.kwargs = {}
   
    def __call__(self,*args,**kwargs):
        if args:
            self.args.extend(args)
            if len(self.args) == self.argsReq:
                targs = list(self.args)
                self.args = []
                return self.func(*targs)
               
        if kwargs:
            self.kwargs.update(kwargs)
            if len(self.kwargs) == self.argsReq:
                tkwargs = self.kwargs.copy()
                self.kwargs = {}
                return self.func(**tkwargs)


If we have a normal function, say sumxy,


def sumxy(x,y):
    return x+y


Now, we can do something like,
csumxy = almost_curry(sumxy)

If we call the our csumxy (its an object, not a function, but, functions are objects, oh I am getting loopy, never mind...)

csumxy(4) #just a normal call
csumxy(5) #target function has got the required number or args, so
9               # it has output the result! yay!

Takeaway: I found one use for the inspect module in python. Pulling this off without getargspec() in inspect would have required some other kind of hackery. If you have any suggestions please comment.

No comments:

Post a Comment