Detect when a class member is updated

Gerhard Häring gerhard.haering at
Wed Jan 15 15:50:54 CET 2003

Steve Holden <sholden at> wrote:
> "Boethius" <boethius at> wrote in message
> news:67446a0a.0301150634.f6d0c43 at
>> Can I detect when a class member is added or updated?
>> I have a class with a member called path. Everytime it's updated, I'd
>> like to run a 'sanity check' on the new value.
>> How can I do this?
> Take a look at "setattr()" generally, and the __setattr__() special method
> inparticular. This allows you to trap access to attributes.

That was necessary before properties were introduced in Python 2.2. So you
might as well write something like:

class MyClass(object):
    def __init__(self):
        self._path = None

    def _get_path(self):
        return self._path

    def _set_path(self, value):
        if isinstance(value, str): # a primitive check
            self._path = value
            raise ValueError

    path = property(_get_path, _set_path)

Note that properties only work with new-style classes (inherited from
object). See for details.

Gerhard Häring
OPUS GmbH München
Tel.: +49 89 - 889 49 7 - 32

More information about the Python-list mailing list