detecting property modification

Mangabasi mangabasi at gmail.com
Fri Dec 21 12:49:51 EST 2007


On Dec 21, 12:40 pm, Jean-Paul Calderone <exar... at divmod.com> wrote:
> On Fri, 21 Dec 2007 09:26:36 -0800 (PST), Mangabasi <mangab... at gmail.com> wrote:
> >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).
>
> You don't need metaclasses.  You do need a wrapper around the list
> so that you can intercept calls to __setitem__ (and whatever else)
> which are made onto it.
>
> You might also consider making Body new-style (subclass object) and
> using a property instead of a __setattr__ implementation.  You still
> need a wrapper, but the implementation of the rest of the feature
> should be simpler.
>
> Jean-Paul- Hide quoted text -
>
> - Show quoted text -

Hi Jean-Paul,

Sorry, I should have spelled this out in my post but I did not.  For
several reasons I do not wish to couple the pos object with the Body
instances.  In my case, I did not want pos objects (in my example they
were lists but they can be other objects as well) to care about their
parents.  So the question is:  How do we detect this in the Body?




More information about the Python-list mailing list