detecting property modification
Jean-Paul Calderone
exarkun at divmod.com
Fri Dec 21 12:40:56 EST 2007
On Fri, 21 Dec 2007 09:26:36 -0800 (PST), Mangabasi <mangabasi 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
More information about the Python-list
mailing list