detecting modifications to an instance? (for debugging)

Ben Hutchings do-not-spam-ben.hutchings at businesswebsoftware.com
Wed Apr 9 09:38:06 EDT 2003


In article <ef08387c.0304082116.e658c31 at posting.google.com>,
Fortepianissimo wrote:
> 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).

It is possible to prevent it.

> Any suggestion is extremely welcome!

Here's how to detect it:

    def __setattr__(self, name, value):
        self.__dict__[name] = value
        print ('in %s instance 0x%x, set %s=%s'
               % (self.__class__.__name__, id(self), name, repr(value)))

    def __delattr__(self, name):
        del self.__dict__[name]
        print ('in %s instance 0x%x, deleted %s'
               % (self.__class__.__name__, id(self), name)

This assumes your class doesn't use __slots__ and doesn't have a
super-class that defines __setattr__ or __delattr__.  If either of
those is true then you should call the super-class implementation
instead of manipulating self.__dict__.

If you want to prevent modifications, you can raise an exception in
those methods, but be aware that these methods will be called even
when you set attributes in __init__, so you would need to manipulate
self.__dict__ there.




More information about the Python-list mailing list