How can I use a class instance variable as an argument for a method decorator in Python? The following is a minimal example shows what I'm trying to do. It obviously fails as the decorator function does not have access to the reference to the instance and I have no idea how to get access to the reference from the decorator.
def decorator1(arg1):
def wrapper(function):
print "decorator argument: %s" % arg1
return function
return wrapper
class Foo(object):
def __init__(self, arg1):
self.var1 = arg1
@decorator1(self.var1)
def method1(self):
print "method1"
foo = Foo("abc")
foo.method1()
It's not going to work; the decorator is called during class creation time, which is long before an instance is created (if that ever happens). So if your "decorator" needs the instance, you have to do the "decorating" at instantiation time:
def get_decorator(arg1):
def my_decorator(function):
print "get_decorator argument: %s" % arg1
return function
return my_decorator
class Foo(object):
def __init__(self, arg1):
self.var1 = arg1
self.method1 = get_decorator(self.var1)(self.method1)
def method1(self):
print "method1"
foo = Foo("abc")
foo.method1()
Note that I changed the function names according to their meanings; the actual "decorator", i.e. the function that (potentially) modifies the method, is wrapper
in your case, not decorator1
.