Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A simple implementation of Pub/Sub Pattern in language python
#!/usr/bin/env python
from collections import defaultdict
class Intermedia:
channels = defaultdict(dict)
def broadcast(cls, channel, msg):
'''broadcast a message to specific subscribers'''
for name, callback in cls.channels[channel].items():
'channel': channel,
'msg': msg,
'name': name
def register(cls, channel, subscriber):
'''register a subscriber into specific channel'''
cls.channels[channel][] = subscriber.callback
def unregister(cls, channel, subscriber):
'''unregister a subscriber from specific channel'''
del cls.channels[channel][]
class Publisher:
def publish(self, channel, msg):
'''publish a message to specific channel'''
Intermedia.broadcast(channel, msg)
class Subscriber:
def __init__(self, name, callback=None): = name
self.callback = callback if callable(callback) else self.callback
def callback(self, msg):
'''default event handler for current subscriber'''
print('Subscriber "{0[name]}" receive message "{0[msg]}" from channel "{0[channel]}"'.format(msg))
def subscribe(self, channel):
'''subscribe specific channel from publisher'''
Intermedia.register(channel, self)
def unsubscribe(self, channel):
'''unsubscribe specific channel from publisher'''
Intermedia.unregister(channel, self)
if __name__ == '__main__':
# initialize objects
Subscribers = {
'a': Subscriber('a'),
'b': Subscriber('b'),
'c': Subscriber('c', lambda msg: print('"{0[name]}": "{0[msg]}" @ {0[channel]}'.format(msg)))
# begin pub/sub procedure
Publisher.publish('cat', 'Cats are so lovely!')
Publisher.publish('dog', 'Dogs are cute, but cats are better!')
Publisher.publish('dog', 'Correction: dogs & cats are both very lovely!')

This comment has been minimized.

Copy link
Owner Author

queensferryme commented Feb 7, 2019

Environment: Python 3.6.7
Expected Output:

Subscriber "a" receive message "Cats are so lovely!" from channel "cat"
"c": "Cats are so lovely!" @ cat
Subscriber "b" receive message "Dogs are cute, but cats are better!" from channel "dog"
"c": "Dogs are cute, but cats are better!" @ dog
"c": "Correction: dogs & cats are both very lovely!" @ dog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.