Due to Python scope rules, a decorated function usually cannot access any variables in the decorator. However, since arbitrary attributes can be assigned to functions, you can do something like the following in the decorator to get a similar effect (due to the same scope rules):
def funcDec(func): localVariable = "I'm a local string" def wrapped(*args): print("Calling localVariable from funcDec " + localVariable) func(*args) print("done with calling f1") wrapped.attrib = localVariable return wrapped @funcDec def f1(x, y): print(x + y) print('f1.attrib: {!r}'.format(f1.attrib)) f1(2, 3)
Which will produce the following output:
Calling localVariable from funcDec I'm a local string 5 f1.attrib: "I'm a local string" done with calling f1
Someone asked if this could be applied to class methods: the answer is yes, but you must refer to the method either through the class itself, or its instance is passed as an argument to self . Both methods are shown below. Using self is preferred because it makes the code independent of the name of the class in which it resides.
class Test(object): @funcDec def f1(self): print('{}.f1() called'.format(self.__class__.__name__)) print('self.f1.attrib: {!r}'.format(self.f1.attrib))
Exit:
Calling localVariable from funcDec I'm a local string Test.f1() called self.f1.attrib: "I'm a local string" Test.f1.attrib: "I'm a local string" done with calling f1
source share