self-aware list of objects able to sense constituent member alterations?

Peter Wang misterwang at gmail.com
Thu Jan 29 07:17:01 CET 2009


On Jan 27, 3:16 pm, Reckoner <recko... at gmail.com> wrote:
> I'm not sure this is possible, but I would like to have
> a list of  objects
>
> A=[a,b,c,d,...,z]
>
> where,  in the midst of a lot of processing I might do something like,
>
> A[0].do_something_which_changes_the_properties()
>
> which alter the properties of the object 'a'.
>
> The trick is that I would like A to be mysteriously aware that
> something about the  object 'a' has changed so that when I revisit A,
> I will know that the other items in the list need to be refreshed to
> reflect the changes in A as a result of changing 'a'.
>
> Even better would be to automatically percolate the subsequent changes
> that resulted from altering 'a' for the rest of the items in the list.
> Naturally, all of these items are related in some parent-child
> fashion.
>
> that might be a lot to ask, however.
>
> Any advice appreciated.

You should really look at Enthought's Traits package.  It does exactly
what you are asking for, and much, much more.  See:

http://code.enthought.com/projects/traits/documentation.php
http://code.enthought.com/projects/traits/examples.php

Using Traits, you could do the following:

from enthought.traits.api import *
class Child(HasTraits):
    state = Enum("happy", "sad", "bawling")

class Parent(HasTraits):
    child = Instance(Child)

    @on_trait_change('child.state')
    def handler(self):
        print "new child state:", self.child.state

bob_jr = Child()
bob = Parent(child = bob_jr)

bob_jr.state = "sad"
# This would result in bob.handler() being called

(Disclosure: I work at Enthought and have been using Traits heavily
for the last 4+ years.)

-Peter



More information about the Python-list mailing list