detecting modifications to an instance? (for debugging)

Michele Simionato mis6 at pitt.edu
Wed Apr 9 11:16:25 EDT 2003


fortepianissimo at yahoo.com.tw (Fortepianissimo) wrote in message news:<ef08387c.0304082116.e658c31 at posting.google.com>...
> I have a big chunk of Python code and I'd like to detect any run-time
> modification to instances of a particular class.
> 
> I'd like to know how to do it with a minimal addition of code, i.e.,
> it's much preferrable to make the code report any such instances
> instead of using a third-party debugging tool for it.
> 



> Note I just want to detect the modification, not to prevent them
> (which I think is impossible in Python).
> 
> Any suggestion is extremely welcome.

Not sure if I understand correctly what you want, but you can control
run-time modification of attributes via __setattr__:

class DetectModification(object):
    def __setattr__(self,x,y):
        print "Trying to set '%s' to %s ..." % (x,y),
        object.__setattr__(self,x,y)
        print "Done"

class C(DetectModification):
    def __init__(self,a):
        self.a=a

c=C(1)
c.a=2
print c.a # => 2

This snipped will warn you when the attribute 'a' is set (once in C.__init__
then in the line c.a=2). You may prevent the modification by raising
an exception in __setattr__.


            Michele




More information about the Python-list mailing list