>我有一个接受 args 和 kwargs 的函数,我需要根据函数中第二个 arg 的值在我的装饰器中做一些事情,就像下面的代码一样:
def workaround_func():
def decorator(fn):
def case_decorator(*args, **kwargs):
if args[1] == 2:
print('The second argument is a 2!')
return fn(*args, **kwargs)
return case_decorator
return decorator
@workaround_func()
def my_func(arg1, arg2, kwarg1=None):
print('arg1: {} arg2: {}, kwargs: {}'.format(arg1, arg2, kwarg1))
问题是python允许用户使用第二个参数作为常规参数或关键字参数调用函数,因此如果用户使用arg2
作为kwarg调用my_func
,则会引发IndexError
,见下文:
In [8]: d.my_func(1, 2, kwarg1=3)
The second argument is a 2!
arg1: 1 arg2: 2, kwargs: 3
In [9]: d.my_func(1, arg2=2, kwarg1=3)
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-9-87dc89222a9e> in <module>()
----> 1 d.my_func(1, arg2=2, kwarg1=3)
/home/camsparr/decoratorargs.py in case_decorator(*args, **kwargs)
2 def decorator(fn):
3 def case_decorator(*args, **kwargs):
----> 4 if args[1] == 2:
5 print('The second argument is a 2!')
6 return fn(*args, **kwargs)
IndexError: tuple index out of range
有没有办法解决这个问题,而不仅仅是做一个try/except
并抓住IndexError
?
我使用python decorator
包找到了答案。该包的一个功能是,无论用户如何传递位置/关键字参数,它都会保留它们。它具有减少大量代码的额外好处,因此我的原始代码:
def workaround_func():
def decorator(fn):
def case_decorator(*args, **kwargs):
if args[1] == 2:
print('The second argument is a 2!')
return fn(*args, **kwargs)
return case_decorator
return decorator
@workaround_func()
def my_func(arg1, arg2, kwarg1=None):
print('arg1: {} arg2: {}, kwargs: {}'.format(arg1, arg2, kwarg1))
成为:
from decorator import decorator
@decorator
def workaround_decorator(f, *args, **kwargs):
if args[1] == 2:
print('The second argument is 2!')
return f(*args, **kwargs)
@workaround_decorator
def my_func(arg1, arg2, kwarg1=None):
print('arg1: {} arg2: {}, kwargs: {}'.format(arg1, arg2, kwarg1))
能想到的最强大的处理方式......诀窍是检查第二个参数的名称。 然后,在装饰器中,检查该名称是否存在于 kwargs
中。 如果是,那么你使用它。 如果否,则使用 args
.
from inspect import getargspec
def decorate(fn):
argspec = getargspec(fn)
second_argname = argspec[0][1]
def inner(*args, **kwargs):
special_value = (kwargs[second_argname]
if second_argname in kwargs else args[1])
if special_value == 2:
print "foo"
else:
print "no foo for you"
return fn(*args, **kwargs)
return inner
@decorate
def foo(a, b, c=3):
pass
foo(1,2,3)
foo(1,b=2,c=4)
foo(1,3,5)
foo(1,b=6,c=5)
运行此操作会导致:
foo
foo
no foo for you
no foo for you
不出所料。