# coding=utf-8
"""Module to allow classes to communicate when an event is produced"""
[docs]class Publisher(object):
"""Base class to provide functionality to notify updates to other objects"""
def __init__(self):
self._subscribers = dict()
[docs] def subscribe(self, who, callback=None):
"""
Add a suscriber to the current publisher
Parameters
----------
who: object
Subscriber to add
callback: callable or None, optional
Callback to call
"""
if callback is None:
callback = getattr(who, 'update')
self._subscribers[who] = callback
[docs] def unsubscribe(self, who):
"""
Remove a suscriber from the current publisher
:param who: suscriber to remove
:type who: object
"""
del self._subscribers[who]
[docs] def dispatch(self, *args):
"""
Notify update to all the suscribers
:param args: arguments to pass
"""
for callback in tuple(self._subscribers.values()):
# noinspection PyCallingNonCallable
callback(*args)
@property
def suscribers(self):
"""List of suscribers of this publisher"""
return self._subscribers.keys()
[docs] def only_suscriber(self, who):
"""
Get if an object is the sole suscriber of this publisher
Parameters
----------
who: object
Returns
-------
bool
"""
if len(self._subscribers) != 1:
return
return who in self._subscribers