The Pub/Sub API

This is the API (and implementation) of a simple Topic class; as used in Use.


class pubsub.Topic

A Topic is like a channel to distribute information (events), in a Pub/Sub environment.

This will decouple the pubsub.AbstractType.Publisher from the pubsub.AbstractType.Subscriber (in both directions).

  • On one side is a Publisher that provides ‘data’ (value’s, events, …).

  • The other side has Subscribers who subscribe to the topic (with callbacks).

  • Both Publisher and Subscriber are abstract types; there is no concrete class (needed).

  • Any module that calls publish() is called a Publisher; likewise, a Subscriber is anyone calling subscribe().

  • Commonly there is only one Publisher (for a given Topic); that is not mandatory, however.

Topic.publish(value, force=False):

This method is called by the Publisher, whenever a new value is to be shared. When force is False (default), the value will only be distributed when it differs from the previous value. To force distribution, set force to True.


This method is called by all Subscribers to register a callback, which is called on new ‘data’.

The passed callback (any callable, like a callback_function_type() callback_method_type()) will be called when ‘data’ is available. It has a signature like:

def callback([self,] value, topic):

Where value is the ‘data’ passed to publish() and ‘topic’ is the Topic instance, use to route it.

When the callback is a method, the self parameter is automagically remembered by Python. For function-callbacks, leave it out.

Supporting types

Both the Publisher and the Subscribers are Abstract Types.

class pubsub.AbstractType.Publisher

Any code that will call pubsub.Topic.publish(). It can be a class, a module or just code …

class pubsub.AbstractType.Subscriber

Everybody calling pubsub.Topic.subscribe(). Typically, the Subscriber has a callback function/method too. See callbacks for an example.

Often, it has a method that acts as the callback.


The generic signature for callbacks is simple:

pubsub.AbstractType.callback_function_type(value, topic)
pubsub.AbstractType.callback_method_type(self, value, topic)


comments powered by Disqus