Is there a clean way to have a decorator call an instance method on a class only at the time an instance of the class is instantiated?
class C:
def instance_method(self):
print('Method called')
def decorator(f):
print('Locals in decorator %s ' % locals())
def wrap(f):
print('Locals in wrapper %s' % locals())
self.instance_method()
return f
return wrap
@decorator
def function(self):
pass
c = C()
c.function()
I know this doesn't work because self
is undefined at the point decorator
is called (since it isn't called as an instance method as there is no available reference to the class). I then came up with this solution:
class C:
def instance_method(self):
print('Method called')
def decorator():
print('Locals in decorator %s ' % locals())
def wrap(f):
def wrapped_f(*args):
print('Locals in wrapper %s' % locals())
args[0].instance_method()
return f
return wrapped_f
return wrap
@decorator()
def function(self):
pass
c = C()
c.function()
This uses the fact that I know the first argument to any instance method will be self
. The problem with the way this wrapper is defined is that the instance method is called every time the function is executed, which I don't want. I then came up with the following slight modification which works:
class C:
def instance_method(self):
print('Method called')
def decorator(called=[]):
print('Locals in decorator %s ' % locals())
def wrap(f):
def wrapped_f(*args):
print('Locals in wrapper %s' % locals())
if f.__name__ not in called:
called.append(f.__name__)
args[0].instance_method()
return f
return wrapped_f
return wrap
@decorator()
def function(self):
pass
c = C()
c.function()
c.function()
Now the function only gets called once, but I don't like the fact that this check has to happen every time the function gets called. I'm guessing there's no way around it, but if anyone has any suggestions, I'd love to hear them! Thanks :)