detecting property modification

Mangabasi mangabasi at gmail.com
Fri Dec 21 12:26:36 EST 2007


Howdy,

I think it is easier to explain my question with a short example:

class Body:
    def __init__(self, pos):
        self.__dict__['pos'] = pos

    def __setattr__(self, name, value):
        if name == 'pos':
            print 'pos changed to', value

       self.__dict__[name] = value

>>> b = Body([0, 0])
>>> b.pos = [3, 4]
>>> pos changed to [3, 4]
>>> b.pos[0] = 5 # How do I detect this in the Body?
>>>


I would like to print 'pos changed to [5, 4]' when pos is modified
with direct access to the pos object (i.e. b.pos[0] = 5)


My first instinct is to modify the Body's __dict__  by using
metaclasses.
I don't have any experience with meta classes but from what I remember
this should be possible but I thought there could be a simpler way to
do this.

What is the Pythonic way to do this?  Can anybody provide a short
example for either case (with or without metaclasses).

Regards





More information about the Python-list mailing list