I’m trying to understand how decorators work, and was wondering if a decorated function can access variables of the decorator. For example, in the following code, how do I make f1 have access to localVariable? Is that possible, and is it even a good way of doing things?
def funcDec(func):
localVariable = "I'm a local string"
def func2Return(*args):
print "Calling localVariable from decorator " + localVariable
func(*args)
print "done with calling f1"
return func2Return
@funcDec
def f1(x, y):
print x + y
print localVariable
f1(2, 3)
No, you can’t. See this previous question. Just because the function is a decorator doesn’t mean functions it calls have special access to its variables. If you do this:
Then otherFunc doesn’t have access to the variable
a. That’s how it works for all function calls, and it’s how it works for decorators too.Now, the wrapper function you define inside the decorator (
func2Returnin your example) does have access to the variables, because that function is lexically in the same scope as those variables. So your lineprint "Calling localVariable from decorator " + localVariablewill work. You can use this to some extent to wrap the decorated function with behavior that depends on variables in the decorator. But the function actually being decorated (f1in your example) doesn’t have access to those variables.A function only has access to local variables from the scope where the function definition actually is. Functions don’t get variables from calling scopes. (This is a good thing. If they did, it would be a huge mess.)