[Python-Dev] Oberver Pattern

Steve Holden sholden@holdenweb.com
Fri, 10 May 2002 16:45:22 -0400


----- Original Message -----
From: "Raymond Hettinger" <python@rcn.com>
To: <python-dev@python.org>
Sent: Friday, May 10, 2002 2:23 PM
Subject: [Python-Dev] Oberver Pattern


> 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.
>
"The object" seems a bit general. Do you mean to attach notification
requests separately to each modifiable piece of state, or have the observer
analyze which particular piece of object state had changed when the
notification call was made?

> 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).
>
Correct me if I'm wrong, that seems pretty much like the Java event
notification model. I could never make my mind up whether that sucked
because Java's such a pain (I have never liked explicit declarations) or
whether it was simply because I didn't like the model. Java's verbosity
certainly makes it a bind having to deal with low-level details like GUI
events, although the flexibility is worthwhile.

> 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.
>
The idea, presumably, being to make the observer protocol implicit at the C
level? I'd only thought of doing this explicitly in Python. It seems like
this testing could have a huge performance penalty.

There's also the issue that the feature might need to interact with
pure-Python objects, which in turn means that notifyall() might end up
calling back into the Python environment. Seems like this might place more
stress on the GIL? Or was your intention to restrict this feature solely to
the C portions of the implementation (new-style classes)? Alex's smart
shelved, being implemented in Python, would clearly need some way (yet more
magic methods?) to hook into this mechanism.

random-thoughts-from-a-random-brain-ly y'rs  - steve
--
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------