Write a program that implements a publish-subscribe messaging system.
- User
Write a program that implements a publish-subscribe messaging system.
Assistant
Write a program that implements a publish-subscribe messaging system.
The user wants a program that implements a publish-subscribe (pub-sub) messaging system. The request is general. It doesn't specify:
Plan:
Define the Core Components:
Subscriber: An interface or base class that defines an update or receive method.Publisher: A class that can publish messages to a specific topic.Broker (or PubSub): The central hub. It maps topics to lists of subscribers.Drafting the Python Code (Mental or Scratchpad):
The Broker:
class Broker:
def __init__(self):
self.topics = {} # topic -> [subscribers]
def subscribe(self, topic, subscriber):
# add subscriber to list
pass
def unsubscribe(self, topic, subscriber):
# remove subscriber
pass
def publish(self, topic, message):
# loop through subscribers for that topic and notify
pass
The Subscriber: Could be a function, or a class. A class is more formal for "Object Oriented Design".
class Subscriber:
def update(self, message):
print(f"Received: {message}")
Refining the Implementation:
Thread Safety: In a real-world scenario, concurrent access is an issue. For a simple example, I should probably stick to single-threaded for clarity, but maybe add a note or a simple lock if I want to be robust. Let's stick to single-threaded for the "Hello World" version, but maybe use collections.defaultdict to make code cleaner.
Async vs Sync: Async is more modern for Python. However, synchronous is easier to understand for a basic algorithmic demonstration. I will provide a synchronous version first.
Structuring the Example:
PubSub: The central engine.Advanced Version (Optional but good):
multiprocessing or asyncio to show how it handles blocking? No, let's stick to the standard pattern first. The "Observer Pattern" is the foundation of Pub/Sub.Writing the Solution:
PubSub class (the Broker).Code Details:
topic (string) and values are lists of callbacks (functions). This is more flexible than forcing a specific Subscriber class.subscribe(topic, callback), publish(topic, data), unsubscribe(topic, callback).Self-Correction during drafting: Handling unsubscribes with function callbacks can be tricky (identity). If I use a class instance, it's easier to manage identity. I'll provide a generic approach using callbacks because it's "Pythonic", but I'll use functools.partial or just simple functions in the example.
Final Code Structure:
class PubSub:
# __init__: map of topic -> set of subscribers
# subscribe(topic, callback): adds to set
# publish(topic, message): iterates and calls
# unsubscribe(topic, callback): removes from set
Adding a "Real-world" twist:
Perhaps a simple asynchronous version using asyncio? It demonstrates the true power of pub/sub (decoupling time/flow).
Decision: I will provide a robust Synchronous version (standard) and a brief Asynchronous version (advanced) to be thorough.
Reviewing the Output:
(Self-Correction for the final output): I will stick to one high-quality, commented synchronous implementation using classes, as it maps best to the theoretical definition of the pattern in most textbooks. I will use collections.defaultdict for cleaner code.
Let's refine the Subscriber part. Using callbacks (functions) is the most flexible way.
subscribe(topic, callback)publish(topic, *args, **kwargs)Let's write the code.
Step 1: The Broker
from collections import defaultdict
class PubSub:
def __init__(self):
self.channels = defaultdict(set)
def subscribe(self, channel, callback):
self.channels[channel].add(callback)
def unsubscribe(self, channel, callback):
if channel in self.channels:
self.channels[channel].discard(callback)
def publish(self, channel, message):
if channel in self.channels:
for callback in self.channels[channel]:
callback(message)
Step 2: The Driver Code Define some listeners. Fire some events.
Step 3: Add Decorator Syntax (Bonus)
It's very Pythonic to allow @broker.subscribe('topic') on a function. I'll add that to make the solution impressive and practical.
Final Plan:
Let's go. Here is a complete, runnable implementation of a Publish-Subscribe (Pub/Sub) system in Python.
This implementation uses an In-Memory Broker pattern. It features:
PubSubBroker): This is the middleman. It maintains a dictionary (self.topics). Think of this as a switchboard operator.subscribe is called, the broker adds the function reference (the callback) to a list associated with that specific string (the topic).publish is called, the broker looks up the topic, finds the list of functions stored there, and executes them one by one, passing the message payload as an argument.In larger applications, you often want to treat Subscribers as Classes rather than just functions. Here is how you might adapt the pattern for classes:
class Subscriber:
def __init__(self, name):
self.name = name
def update(self, message):
print(f"{self.name} received: {message}")
# Usage
s1 = Subscriber("Client A")
s2 = Subscriber("Client B")
# We pass the method 's1.update' as the callback
broker.subscribe("news", s1.update)
broker.subscribe("news", s2.update)
broker.publish("news", "Breaking: Python is awesome!")
If you are building this for a production-grade system (like a chat app or microservices architecture), you would need to address two things this simple code does not handle:
publish() runs the subscriber functions synchronously. If a subscriber takes 10 seconds to run, the entire system freezes. In Python, you would typically use asyncio or threading so the publisher can fire-and-forget without waiting.import logging
# Configure logging to see the output clearly
logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s')
class PubSubBroker:
"""
The central hub that manages topics and subscribers.
"""
def __init__(self):
# Dictionary to store the mapping of topics to subscribers
# Structure: { "topic_name": set([subscriber_func_1, subscriber_func_2]) }
self.topics = {}
def subscribe(self, topic, subscriber_callback):
"""
Register a callback function for a specific topic.
"""
if topic not in self.topics:
self.topics[topic] = set()
self.topics[topic].add(subscriber_callback)
logging.info(f"New subscription to topic: '{topic}'")
def unsubscribe(self, topic, subscriber_callback):
"""
Remove a callback function from a specific topic.
"""
if topic in self.topics and subscriber_callback in self.topics[topic]:
self.topics[topic].remove(subscriber_callback)
logging.info(f"Unsubscribed from topic: '{topic}'")
def publish(self, topic, message):
"""
Send a message to all subscribers of a specific topic.
"""
if topic not in self.topics:
logging.warning(f"Published to non-existent topic: '{topic}'")
return
# Log the broadcast
logging.info(f"Broadcasting on '{topic}': {message}")
# Notify all subscribers
# We use list() to make a copy, allowing modifications during iteration if needed
subscribers = list(self.topics[topic])
for callback in subscribers:
try:
callback(message)
except Exception as e:
logging.error(f"Error in subscriber callback: {e}")
# --- Usage Example ---
# 1. Create the Broker (The System)
broker = PubSubBroker()
# 2. Define Subscribers (Listeners)
# These can be simple functions...
def email_service_logger(message):
print(f" [Email Service] Logging email request: {message}")
def user_notification(message):
print(f" [User Phone] Notifying user with: {message}")
# ... or more complex logic
def database_archiver(message):
print(f" [Database] Saving message to history: '{message}'")
# 3. Subscribe to Topics
# email_service_logger and user_notification care about "new_user" events
broker.subscribe("new_user", email_service_logger)
broker.subscribe("new_user", user_notification)
# database_archiver cares about "system_alert"
broker.subscribe("system_alert", database_archiver)
print("\n--- Scenario 1: New User Signs Up ---")
# The Publisher (e.g., a web controller) publishes an event
broker.publish("new_user", "Alice has joined the platform!")
print("\n--- Scenario 2: System Alert ---")
# Only the database listens to this
broker.publish("system_alert", "CPU Usage at 90%")
print("\n--- Scenario 3: Unsubscribing ---")
# The email service stops listening to new users
broker.unsubscribe("new_user", email_service_logger)
broker.publish("new_user", "Bob has joined the platform!")
# Note: Email service did not print this time