# coding=utf-8 class Publisher(object): """ Base class to provide functionality to notify updates to other objects """ def __init__(self): self._subscribers = dict() def subscribe(self, who, callback=None): """ Add a suscriber to the current publisher :param who: subscriber to add :type who: object :param callback: method to execute when publisher updates :type callback: callable | NoneType """ if callback is None: callback = getattr(who, 'update') self._subscribers[who] = callback def unsubscribe(self, who): """ Removes a suscriber from the current publisher :param who: suscriber to remove :type who: object """ del self._subscribers[who] def dispatch(self, *args): """ Notify update to all the suscribers :param args: arguments to pass """ for subscriber, callback in self._subscribers.items(): callback(*args) def suscribers(self, *args): """ Notify update to all the suscribers :param args: arguments to pass """ return self._subscribers.keys()