traceing object usage: how to trace attribute access

Michele Simionato mis6 at pitt.edu
Thu Mar 6 12:09:43 EST 2003


Volker Apelt <gq437x at yahoo.de> wrote in message news:<lgvfyxaonp.fsf at mu.biosolveit.local>...
> I am looking for ways to trace all kind of access to objects
> of some class with least impact on the traced class and 
> no impact on the caller.


I posted this yesterday, but didn't show up (?), therefore I will repost.

A possibility is to use properties + a custom metaclass, as in this simple
example:

class TracedAccess(type):
    def __init__(cls,name,bases,dic):
        for key,value in dic.iteritems():
            def get(self,k=key,v=value):
                print "You are getting attribute %s, value=%s" % (k,v)
                return v
            def set(self,val,k=key):
                print "You are setting attribute %s to %s" % (k,val)
            setattr(cls,key,property(get,set))


class B(object):
    __metaclass__=TracedAccess
    a1='x'
    a2='y'
    
b=B()

b.a1
b.a2
b.a1='z'

# Output:
# You are getting attribute a1,value=x
# You are getting attribute a2,value=y
# You are setting attribute a1 to z

Further work is needed for tracing methods, but this should give you a
starting point. Notice that the approach works well with inheritance,  except
for the tricky point that 'super' doesn't work with properties.

                                  Michele




More information about the Python-list mailing list