def decorator(func): def wrapper(): func() print(func.a) return wrapper @decorator def…
- User
def decorator(func):
def wrapper(): func() print(func.a)
return wrapper
@decorator def test(): test.a = 23
test()
Error, there is no such attribute in the function. How do I access a function's local variable in a decoror?
- Assistant
To access a function's attribute within a decorator, you should define the attribute before applying the decorator because the decorator is applied at the time of function definition. So, to make sure the attribute is available, assign it directly to the function object before decorating.
However, the code snippet you provided has a couple of issues related to when and how the attribute is added to the function. You are attempting to add an attribute
ato the functiontestinside its own body. This doesn't work as intended because whentest()is called, the decoratorwrapperfunction is what actually gets executed, and only then does it try to execute . However, inside is neither executed before the decorator applies nor is it accessible the way you intend.