[Python-Dev] Generic notifier module

Fredrik Lundh Fredrik Lundh" <effbot@telia.com
Wed, 19 Apr 2000 19:15:28 +0200


Ka-Ping Yee <ping@lfw.org> wrote:
> I think it would be very nice for the Python standard library to
> provide a messaging mechanism (you may know it as signals/slots,
> publish/subscribe, listen/notify, etc.).

your notifier looks like a supercharged version of the "Observer"
pattern [1].  here's a minimalistic observer mixin from "(the eff-
bot guide to) Python Patterns and Idioms" [2].

class Observable:

    __observers =3D None

    def addobserver(self, observer):
        if not self.__observers:
            self.__observers =3D []
        self.__observers.append(observer)

    def removeobserver(self, observer):
        self.__observers.remove(observer)

    def notify(self, event):
        for o in self.__observers or ():
            o(event)

notes:

-- in the GOF pattern, to "notify" is to tell observers that something
happened, not to register an observer.

-- GOF uses "attach" and "detach" to install and remove observers;
the pattern book version uses slightly more descriptive names.

-- the user is expected to use bound methods and event instances
(or classes) to associate data with the notifier and events.  earlier
implementations were much more elaborate, but we found that the
standard mechanisms was more than sufficient in real life...

</F>

1) "Design Patterns", by Gamma et al.
2) http://www.pythonware.com/people/fredrik/patternbook.htm