[Persistence-sig] Observing object changes
Lamy Jean-Baptiste
jiba@tuxfamily.org
Tue, 13 Aug 2002 14:25:54 +0200 (CEST)
Hi everyone,
I've just see the new persistance-SIG and i realize i have already worked
on observing object changes. I use it for updating graphical interfaces
when objects are changed, and for debugging, but it appears it can be
usefull for OO database too -- so such a feature would rock !
Here is the API i use:
addevent (obj, func) -- Add the event FUNC (=an observer) to OBJ
removeevent(obj, func) -- Remove the event FUNC from OBJ
FUNC is a callable which is then called each time OBJ is modified. It takes
4 arguments: the modified object, the name of the modified attribute, the
new value and the old value.
Example of use:
class Point:
def __init__(self, x, y): self.x, self.y = x, y
def event(obj, attr, new, old):
print attr, "was", old, "is now", new
p = Point(0.0, 0.0)
addevent(p, event)
p.x = 1.0
# print "x was 0.0 is now 1.0"
I have already written a pure Python implementation of that (feel free to
ask for the code if you're interested); it works well but it is really an
ugly hack ! The principle is to change the class of the observed object to
a new class that define a __setattr__ method.
However, the interest of this approach is that it work for ANY object
(including list and dict, and already existent object); the object doesn't
have to be designed to fit it (e.g. the Point class above was not written
especially to fit a particular observation framework).
I wonder if it is possible to write a more cleaner version of it in C...?
I hope this helps. Please don't strike me if i am off-topic ;-)
Jiba