Currying decorator in python

前端 未结 9 1697
故里飘歌
故里飘歌 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 04:01

    The solution from Roger Christman will not work with every constellation. I applied a small fix to also handle this situation:

    curried_func(1)(2,3)
    

    The small fix that makes it work with every constellation lies in the returned lambda:

    def curried(func):
        def curry(*args):
            if len(args) == func.__code__.co_argcount:
                ans = func(*args)
                return ans
            else:
                return lambda *x: curry(*(args+x))
        return curry
    
    0 讨论(0)
  • 2020-12-03 04:05

    The below implementation is naive, google for "currying python" for more accurate examples.

    def curry(x, argc=None):
        if argc is None:
            argc = x.func_code.co_argcount
        def p(*a):
            if len(a) == argc:
                return x(*a)
            def q(*b):
                return x(*(a + b))
            return curry(q, argc - len(a))
        return p
    
    @curry
    def myfun(a,b,c):
        print '%d-%d-%d' % (a,b,c)
    
    
    
    myfun(11,22,33)
    myfun(44,55)(66)
    myfun(77)(88)(99)
    
    0 讨论(0)
  • 2020-12-03 04:06

    One-liner just for fun:

    from functools import partial
    curry = lambda f: partial(*[partial] * f.__code__.co_argcount)(f)
    
    @curry
    def add(x, y, z):
        return x + y + z
    
    print(add(2)(3)(4))
    # output = 9
    
    0 讨论(0)
提交回复
热议问题