Notify of change to list

Alan J. Salmoni salmoni at gmail.com
Fri Jun 13 05:00:17 CEST 2008


Hello everyone,

I searched through groups to find an appropriate answer to this one
but could only find these which didn't meet my program's needs:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/53a0bfddeedf35b2/5e4b7119afa5f8df?lnk=gst&q=monitor+change+in+mutable#5e4b7119afa5f8df,
http://groups.google.com/group/comp.lang.python/browse_thread/thread/b7e0bb2cf9e2f5cd/bccfd49a5c8a56e2?lnk=gst&q=monitor+change+in+object#bccfd49a5c8a56e2.

My question is how can my program be notified of a change to a class
attribute that is a list? I have a class defined that has a list as an
attribute and the program needs to know when the user changes this
attribute either completely or elementwise via an interpreter built-in
to the program. Using __setattr__ I can be informed whenever it is
rebound (x.attr = [2,3,4]) but not when changes are made elementwise
(x.attr[1] = 99). I tried using properties to get changes but again
the same result occurs.

class c(object):
    def __init__(self):
        self._x = 0

    def getx(self):
        return self._x

    def setx(self, x):
        print "setting x: ", x
        self._x = x

    x = property(getx, setx)

# all of the following need to be caught
a.x = [1,2,3] # is rebound from 0 so is caught
a.x[1] = 99 # element-wise change only which isn't caught
a.x = [4,5,6] # is rebound so is caught
a.x[0:3] = [11,12,13] # though a "complete" change in terms of
elements, this is element-wise and is not rebound and is thus not
caught
>>>
setting x:  [1, 2, 3]
setting x:  [4, 5, 6]

>From what I understand, changes will only be caught if the attribute
is completely rebound (ie, completely re-assigned), but I cannot force
my users to do this. Short of hacking around with the interpreter to
catch element-wise reassignments (possible, but I'd rather avoid), can
anyone suggest a way to do this?

Alan



More information about the Python-list mailing list