list property fires get on append

Carl Banks pavlovevidence at gmail.com
Sun Jan 6 11:36:57 EST 2008


On Sun, 06 Jan 2008 00:31:13 -0800, Soviut wrote:
> I figured that an append would be treated as a set since I'm adding to
> the list.  But what you say makes sense, although I can't say I'm happy
> with the behaviour.  Is there any way I can get the append to fire a
> set?  I'm thinking of properties from my C# background where i believe
> that manipulation such this would be considered a set.

You'd have to have to hook into the container object itself to detect the 
modification.  This might be pretty workable for you since it's an 
internal object.  Basically, instead of using a list, use a special list-
like object that notifies it's owner when it changes.  Here's a simple 
example to point you in the right direction:


class NotifierList(list):
     def __init__(self,*args,**kwargs):
         super(NotifierList,self).__init__(*args,**kwargs)
         self.watchers = []
     def add_watcher(self,watcher):
         self.watchers.append(watcher)
     def _notify_watchers(self):
         for watcher in self.watchers:
             watcher.object_changed(self)
     def append(self,value):
         super(NotifierList,self).append(value)
         self._notify_watchers()
     # override all other mutating calls, including __setitem__
     # left as exercise


class Hierarchy(object):
    def __init__(self):
        self.children = NotifierList()
        self.children.add_watcher(self)
    def object_changed(self,obj):
        print "self.children modified"
    # no need to make children a property then
    # unless you want to trap rebinding it to new object also


A couple other minor suggestions:

print is a statement, not a function.  You should write

print "GETTING"

not

print("GETTING")

The latter works, but it will cease to work if you want to print more 
than one thing.  Note that print is scheduled to become a function in 
Python 3.0, but for now it's a statement.

Based on the name of your class and typical usage, I'm guessing that you 
probably want _children to be an instance attribute rather than a class 
attribute, so I redid it that way, but .)


P.S. Is calling a method called "firing" in C#?


Carl Banks



More information about the Python-list mailing list