我试图在包装函数中访问我的装饰器参数,但没有成功。
我有的是:
def my_decorator(arg1=False, arg2=None):
def decorator(method):
@functools.wraps(method)
def wrapper(method, *args, **kwargs):
# do something based on arg1 and arg2
# accessing one of the two named arguments
# ends up in a 'referenced before assignment'
arg1 = arg1 # error
arg2 = arg2 # error
newarg1 = arg1 # working
newarg2 = arg2 # working
return method(*args, **kwargs)
return wrapper
return decorator
我会像普通装饰器一样使用它
@my_decorator(arg1=True, arg2='a sting or whatever else')
the_function()
我真的不明白为什么我不能访问装饰器参数。
最佳答案
您可以访问 arg1
和 arg2
,但是您不应该为这些名称赋值,即使使用“增强的”赋值运算符也不行,因为这会使它们成为局部变量内部功能。您收到的错误消息表明您正试图这样做(尽管您没有显示您的代码)。
在 Python 3 中,您可以使用以下方法解决此问题
nonlocal arg1, arg2
wrapper()
中的某处。
关于python - 在装饰器包装器函数中访问装饰器参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4962932/