Python Observer Pattern: Examples, Tips? [closed]

However it does lack flexibility.

Well… actually, this looks like a good design to me if an asynchronous API is what you want. It usually is. Maybe all you need is to switch from stderr to Python’s logging module, which has a sort of publish/subscribe model of its own, what with Logger.addHandler() and so on.

If you do want to support observers, my advice is to keep it simple. You really only need a few lines of code.

class Event(object):

class Observable(object):
    def __init__(self):
        self.callbacks = []
    def subscribe(self, callback):
    def fire(self, **attrs):
        e = Event()
        e.source = self
        for k, v in attrs.iteritems():
            setattr(e, k, v)
        for fn in self.callbacks:

Your Job class can subclass Observable. When something of interest happens, call"progress", percent=50) or the like.

Leave a Comment