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

greywine at gmail.com greywine at gmail.com
Fri Feb 6 15:36:00 CET 2009


On Jan 28, 4:37 am, John O'Hagan <m... at johnohagan.com> wrote:
> On Tue, 27 Jan 2009, Reckoner 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.
>
> [...]
>
> Interesting question.
>
> Maybe this is too simple for your purpose (or maybe just wrong!), but could
> you subclass list and give it an "update" method which keeps a dictionary of
> the state of its members and/or calls another method that makes the
> appropriate changes in the other members when a change occurs, something
> like:
>
> class SelfAwareList(list):
>
>     state_dict = {}
>
>     def update(self):
>         for i in self:
>             if i.state == 'some_condition':
>                 self.do_stuff_to_other_members()
>             self.state_dict[i] = i.state
>
>     def do_stuff_to_other_members(self):
>         print 'doing stuff...'
>
> ?
>
> You could manually call update() on the SelfAwareList instance after calling a
> method on a SelfAwareList member, or even build it into the members' methods
> so that it was automatic.
>
> HTH,
>
> John

Hi Reckoner & John O'Hagan,

Great thread, very interesting.

John, I haven't seen anything like your class that uses list instead
of object and refers to state directly (i.state in self).  Could you
elaborate?  Here would be my implementation of your idea:

class SelfAwareList2(object):

    def __init__(self, l):
        self.l = l
        self.changed = [False for element in l]

    def __str__(self):
        return str(self.l)

    def update(self, index, value):
        self.l[index] = value
        self.changed[index] = True

    def do_stuff_to_other_members(self):
        for i in self.changed:
            if i==False:
                self.l[i] += 1

Here you can print and whenever you update your list, self.changed
keeps track of what changed.  Later on you can call do_stuff_to_others
which in this case adds 1 to each other element.

I assume that your class replaces the awkwardness of l.update(0, 5)
with l[0] = 5, but I can't quite wrap my mind around it.

Luther.



More information about the Python-list mailing list