如何让装饰器处理任意参数

How to get the decorator handle arbitrary arguments

我正在尝试了解装饰器。我想定义一个可以处理任意参数的装饰器。我正在尝试以下操作:

def a_decorator_passing_arbitrary_arguments(function_to_decorate):
    def a_wrapper_accepting_arbitrary_arguments(*args,**kwargs):
        print('The positional arguments are', args)
        print('The keyword arguments are', kwargs)
        function_to_decorate(*args)
    return a_wrapper_accepting_arbitrary_arguments

这是基于 this tutorial 的,据说它可以处理任何类型的参数。但是,当我仅传递关键字参数时,我得到以下带有函数 f(a,b,c):

的输出
@a_decorator_passing_arbitrary_arguments
def f(a,b,c):
    print("The arguments here are the following: {0}, {1}, {2}.".format(a,b,c))

f(a='ali', b='emma', c='t')

输出:

The positional arguments are ()
The keyword arguments are {'a': 'ali', 'b': 'emma', 'c': 't'}

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-cc5ee8d7120a> in <module>
----> 1 f(a='ali', b='emma', c='t')

<ipython-input-1-af03800e2abd> in a_wrapper_accepting_arbitrary_arguments(*args, **kwargs)
      3         print('The positional arguments are', args)
      4         print('The keyword arguments are', kwargs)
----> 5         function_to_decorate(*args)
      6     return a_wrapper_accepting_arbitrary_arguments

TypeError: f() missing 3 required positional arguments: 'a', 'b', and 'c'

当所有变量都作为关键字参数传递时,如何避免出现此错误?

您目前只将位置参数传递给包装函数,而不是关键字参数。

def a_decorator_passing_arbitrary_arguments(function_to_decorate):
    def a_wrapper_accepting_arbitrary_arguments(*args,**kwargs):
        print('The positional arguments are', args)
        print('The keyword arguments are', kwargs)
        # function_to_decorate(*args)  # Wrong
        return function_to_decorate(*args, **kwargs)  # Right
    return a_wrapper_accepting_arbitrary_arguments

(您还应该 return 包装器中的任何 function_to_decorate returns。)