Currying decorator in python

前端 未结 9 1808
故里飘歌
故里飘歌 2020-12-03 03:11

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          


        
9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 03:59

    I think I've got a better one:

    def curried (function):
        argc = function.__code__.co_argcount
    
        # Pointless to curry a function that can take no arguments
        if argc == 0:
            return function
    
        from functools import partial
        def func (*args):
            if len(args) >= argc:
                return function(*args)
            else:
                return partial(func, *args)
        return func
    

    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.

提交回复
热议问题