Tiny pub-sub (observer) pattern implementation.
from tinypubsub.simple import SimplePublisher
publisher = SimplePublisher()
subscription = publisher.subscribe(lambda message: print(message))
publisher.publish("Hello!")
publisher.unsubscribe(subscription)Or:
from tinypubsub.simple import SimplePublisher
publisher = SimplePublisher()
with publisher.subscribe(lambda message: print(message)):
publisher.publish("Hello!")tinypubsub.Publisherhas abstract methods:publish,subscribe,unsubscribe,unsubscribe_all.tinypubsub.simple.SimplePublisher: Dict-based implementation ofPublisher.tinypubsub.weakref.WeakrefPublisher: WeakKeyDictionary-based implementation ofPublisher.
Abstract publisher class.
Type of message that will be published.
Publish message to subscribers.
Add subscriber.
Delete subscriber.
Delete all subscribers.
Return value of Publisher.subscribe().
It can be used as a context manager as:
with publisher.subscribe(...) as subscription:
...and subscription.unsubscribe() will be called when exit.
subscription.unsubscribe() is the same as publisher.unsubscribe(subscription), where subscription = publisher.subscribe(...).
Implementation of Publisher[Message].
Implementation of Publisher[Message].
This implementation uses WeakKeyDictionary to manage subscribers. This may prevent a memory leak if subscription loses all strong references before unsubscribed:
publisher = WeakrefPublisher()
subscription = publisher.subscribe(...)
assert len(publisher._subscribers) == 1
del subscription
assert len(publisher._subscribers) == 0Note that the unsubscribe method will not be called in the above case,
so normally you should unsubscribe explicitly or use context manager.