im trying to access my decorators arguments inside the wrapper function with no luck.
what i have is:
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
and i would use it like a normal decorator
@my_decorator(arg1=True, arg2='a sting or whatever else')
the_function()
i really don't understand why i can't access the decorators arguments.
You can access
arg1
andarg2
, but you should not assign to these names, not even with "augmented" assign operators, because this would make them local variables in the inner function. The error message you get shows that you tried to do exactly this (though you did not show your code).In Python 3, you can work around this problem using
somewhere in
wrapper()
.