gpt4 book ai didi

python - 解析装饰器中的args和kwargs

转载 作者:行者123 更新时间:2023-12-03 16:07:02 24 4
gpt4 key购买 nike

我有一个接受args和kwargs的函数,我需要根据该函数中 2nd 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允许用户使用第二个参数作为常规参数或关键字参数来调用函数,因此,如果用户使用 my_func作为kwarg调用 arg2,则会引发 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 包找到了答案。该软件包的一个功能是,无论用户如何传递,它都会保留位置/关键字args。它具有减少大量代码的额外好处,因此我的原始代码为:

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))

关于python - 解析装饰器中的args和kwargs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18906760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com