I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.
This is an old question but came across venusian. http://venusian.readthedocs.org/en/latest/
It seems to have the ability to decorate methods and give you access to both the class and the method while doing so.
Note tht calling setattr(ob, wrapped.__name__, decorated) is not the typical way of using venusian and somewhat defeats the purpose.
Either way... the example below is complete and should run.
import sys
from functools import wraps
import venusian
def logged(wrapped):
def callback(scanner, name, ob):
@wraps(wrapped)
def decorated(self, *args, **kwargs):
print 'you called method', wrapped.__name__, 'on class', ob.__name__
return wrapped(self, *args, **kwargs)
print 'decorating', '%s.%s' % (ob.__name__, wrapped.__name__)
setattr(ob, wrapped.__name__, decorated)
venusian.attach(wrapped, callback)
return wrapped
class Foo(object):
@logged
def bar(self):
print 'bar'
scanner = venusian.Scanner()
scanner.scan(sys.modules[__name__])
if __name__ == '__main__':
t = Foo()
t.bar()