Instrumenting a class to see how it is used

Michele Simionato michele.simionato at gmail.com
Thu May 10 12:08:33 EDT 2012


This may get you started (warning: not really tested).

$ echo instr.py
from warnings import warn

oget = object.__getattribute__
tget = type.__getattribute__

class Instr(object):

    class __metaclass__(type):        
        def __getattribute__(cls, name):
            clsname = tget(cls, '__name__')
            warn('accessing %s.%s' % (clsname, name), stacklevel=2)
            return tget(cls, name)

    def __getattribute__(self, name):
        warn('accessing %s.%s' % (self, name), stacklevel=2)
        return oget(self, name)


Then change the base classes of the class you want to instrument, i.e.

class MyClass(MyBase) -> class MyClass(MyBase, Instr)

and see what happens. It should work in simple cases.
It will log a lot, so will have to adapt this.



More information about the Python-list mailing list