PyPubSub

4.0.7 · active · verified Thu Apr 16

PyPubSub is a lightweight, thread-safe publish-subscribe messaging library for Python. It provides a simple API to enable decoupled communication between different parts of an application. The current version is 4.0.7, focusing on Python 3 compatibility and performance. Releases typically happen as needed to address bug fixes, new Python version compatibility, or major feature/protocol changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to subscribe functions to a topic and publish messages. Listeners can accept positional and keyword arguments, matching the arguments passed to `sendMessage`. The `pub` object manages all subscriptions and publications.

from pubsub import pub

def listener_a(arg1, arg2='default'):
    print(f"Listener A received: {arg1=}, {arg2=}")

def listener_b(arg1, **kwargs):
    print(f"Listener B received: {arg1=}, kwargs: {kwargs}")

# Subscribe listeners to a topic
pub.subscribe(listener_a, 'my_topic')
pub.subscribe(listener_b, 'my_topic')

# Publish a message to the topic
pub.sendMessage('my_topic', arg1='hello', arg2='world')
pub.sendMessage('my_topic', arg1='another_message', extra_key=123)

# Unsubscribe a listener
pub.unsubscribe(listener_a, 'my_topic')
pub.sendMessage('my_topic', arg1='after_unsubscribe')

view raw JSON →