python中的咖喱装饰器 [英] Currying decorator in python

查看:68
本文介绍了python中的咖喱装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用python写一个可弯曲的装饰器,我想我的基本思想已经下降,但是仍然有一些情况无法正常工作...

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)

在以下情况下失败:

myfun(6)(7)

任何有关如何正确执行此操作的指针将不胜感激!

Any pointers on how to correctly do this would be greatly appreciated!

谢谢!

推荐答案

下面的实现是幼稚的,google提供了 currying python作为更准确的示例。

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)

这篇关于python中的咖喱装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆