The Pub/Sub API¶
This is the API (and implementation) of a simple Topic
class; as used in Use.
Topic¶
- 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 thepubsub.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
andSubscriber
are abstract types; there is no concrete class (needed).Any module that calls
publish()
is called aPublisher
; likewise, aSubscriber
is anyone callingsubscribe()
.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), thevalue
will only be distributed when it differs from the previous value. To force distribution, set force to True.
- Topic.subscribe(callback):
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 theTopic
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, theSubscriber
has a callback function/method too. See callbacks for an example.Often, it has a method that acts as the callback.
callbacks¶
The generic signature for callbacks is simple:
- pubsub.AbstractType.callback_function_type(value, topic)¶
- pubsub.AbstractType.callback_method_type(self, value, topic)¶