我正在编写一个将关键字参数添加到包装函数的装饰器。在此示例中,装饰器添加关键字deco0deco1

def my_decorator(f):
    def inner(arg0, *args, deco0='deco0', deco1='deco1', **kwargs):
        """We assume decoarted functions will take at least one positional arg0"""
        print("Decorated({}, {})".format(deco0, deco1))
        return f(arg0, *args, **kwargs)
    return inner

@my_decorator
def add2(x):
    return x + 2

@my_decorator
def my_mult(x, y):
    return x * y

if __name__ == '__main__':
    print(add2(5))
    print(add2(5, deco0='BLA'))
    print(my_mult(2, 10))
    print(my_mult(2, 10, deco1='BLAM'))


预期结果:

Decorated(deco0, deco1)
7
Decorated(BLA, deco1)
7
Decorated(deco0, deco1)
20
Decorated(deco0, BLAM)
20


装饰器返回的inner函数签名与python2不兼容:

File "./deco.py", line 5
  def inner(arg0, *args, deco0='deco0', deco1='deco1', **kwargs):
                             ^
SyntaxError: invalid syntax


Python2中是否有一种设计模式可以方便装饰器添加关键字参数?还是更好,同时兼容Python2和Python3的模式?

最佳答案

我认为您必须在内部函数内执行诸如Modify kwargs之类的操作:

def inner(arg0, *args, **kwargs):
    deco0 = kwargs.pop('deco0', 'deco0')
    deco1 = kwargs.pop('deco1', 'deco1')
    print("Decorated({}, {})".format(deco0, deco1))
    return f(arg0, *args, **kwargs)

关于python - Python装饰器,添加了与Python2和Python3的关键字参数兼容性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52189910/

10-13 02:15