Wednesday, July 30, 2008

Python publish subscribe

In keeping with the theme of my previous post, I'd like to mention that the publish-subscribe event pattern can also be used in Python. The zope.event package provides this functionality. For example, If I want to publish a topic when Blog objects in my application are updated, I could do something like:

import zope.event

class Blog:
def update(self):

This will send a notification to anyone in my application that has a subscription to blogupdate. To subscribe to this topic, we could do something like:

import zope.event

def sub_blogupdate():
log('Blog updated.')

The subscription would obviously do something more important but this serves well to illustrate the general concept. Publish-subscribe comes in handy when there is a chain of complex events. The zope.event package, although very simplistic, allows us to produce higher quality code.