Notify of change to list
Paul Hankin
paul.hankin at gmail.com
Thu Jun 12 23:19:19 EDT 2008
On Jun 13, 12:00 pm, "Alan J. Salmoni" <salm... at gmail.com> wrote:
> My question is how can my program be notified of a change to a class
> attribute that is a list?
You can't. But you can replace lists inside your class with a list
that notifies changes.
Something like this:
class NotifyingList(list):
def __setitem__(self, i, v):
print 'setting', i, 'to', v
list.__setitem__(self, i, v)
[[You'll likely need to redefine __setslice__, __delitem__,
__delslice__, append and extend as well]].
>>> x = NotifyingList([1, 2, 3])
>>> x[1] = 4
setting 1 to 4
>>> x
[1, 4, 3]
If users of your class are allowed to replace attributes with their
own lists, you'll have to catch these and convert to NotifyingLists;
and it may be somewhat messy.
I hope this is useful to you.
--
Paul Hankin
More information about the Python-list
mailing list