[Python-Dev] Oberver Pattern

Raymond Hettinger python@rcn.com
Fri, 10 May 2002 14:23:09 -0400


I would like to know what you all think about formalizing an observer
protocol for python objects.

A possible implementation would add Py_TPFLAGS_OBSERVABLE and a slot,
tp_observer, with a function, PyObject_GenericAttach which registers a
callable to be notified when the object updates.

Another approach would be to keep a single registry list with access
functions:  attach(subject,observer), detach(subject,observer), and
notifyall(subject).  PyObject_HEAD would have a field, int being_observed=0.
The attach() function sets being_observed.  Any code affecting object state
is obliged to call PyObject_NOTIFY, a macro that checks being_observed and,
if set, calls notifyall(subject).

Alex's smart shelves provide an immediate application -- it needs to know
which of its cache objects have changed state.  Another application would be
to enable computation caching in my matrix package which needs to invalidate
the cache whenever a matrix element gets updated.


Raymond Hettinger