Skip to content
Snippets Groups Projects
Commit 3e7d72c2 authored by Paul McCarthy's avatar Paul McCarthy
Browse files

The Notifier class now allows notifiers to be grouped by 'topic'.

parent 25145d18
No related branches found
No related tags found
No related merge requests found
...@@ -19,11 +19,18 @@ import props ...@@ -19,11 +19,18 @@ import props
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
DEFAULT_TOPIC = 'default'
"""Topic used when the caller does not specify one when registering,
deregistering, or notifying listeners.
"""
class Notifier(object): class Notifier(object):
"""The ``Notifier`` class is a mixin which provides simple notification """The ``Notifier`` class is a mixin which provides simple notification
capability. Listeners can be registered/deregistered via the capability. Listeners can be registered/deregistered to listen via the
:meth:`register` and :meth:`deregister` methods, and notified via :meth:`register` and :meth:`deregister` methods, and notified via the
the :meth:`notify` method. :meth:`notify` method. Listeners can optionally listen on a specific
*topic*, or be notified for all topics.
.. note:: The ``Notifier`` class stores ``weakref`` references to .. note:: The ``Notifier`` class stores ``weakref`` references to
registered callback functions, using the :class:`WeakFunctionRef` registered callback functions, using the :class:`WeakFunctionRef`
...@@ -35,37 +42,53 @@ class Notifier(object): ...@@ -35,37 +42,53 @@ class Notifier(object):
instance. instance.
""" """
new = object.__new__(cls) new = object.__new__(cls)
new.__listeners = collections.OrderedDict() new.__listeners = collections.defaultdict(collections.OrderedDict)
return new return new
def register(self, name, callback): def register(self, name, callback, topic=None):
"""Register a listener with this ``Notifier``. """Register a listener with this ``Notifier``.
:arg name: A unique name for the listener. :arg name: A unique name for the listener.
:arg callback: The function to call - must accept this ``Notifier`` :arg callback: The function to call - must accept this ``Notifier``
instance as its sole argument. instance as its sole argument.
:arg topic: Optional topic on which fto listen for notifications.
""" """
if topic is None:
topic = DEFAULT_TOPIC
# We use a WeakFunctionRef so we can refer to # We use a WeakFunctionRef so we can refer to
# both functions and class/instance methods # both functions and class/instance methods
self.__listeners[name] = props.WeakFunctionRef(callback) self.__listeners[topic][name] = props.WeakFunctionRef(callback)
log.debug('{}: Registered listener {} (function: {})'.format( log.debug('{}: Registered listener {} '
type(self).__name__, '[topic: {}] (function: {})'.format(
name, type(self).__name__,
getattr(callback, '__name__', '<callable>'))) name,
topic,
getattr(callback, '__name__', '<callable>')))
def deregister(self, name): def deregister(self, name, topic=None):
"""De-register a listener that has been previously registered with """De-register a listener that has been previously registered with
this ``Notifier``. this ``Notifier``.
:arg name: Name of the listener to de-register. :arg name: Name of the listener to de-register.
:arg topic: Topic on which the listener was registered.
""" """
callback = self.__listeners.pop(name, None) if topic is None:
topic = DEFAULT_TOPIC
listeners = self.__listeners.get(topic, None)
# Silently absorb invalid topics
if listeners is None:
return
callback = listeners.pop(name, None)
# Silently absorb invalid names - the # Silently absorb invalid names - the
# notify function may have removed gc'd # notify function may have removed gc'd
...@@ -73,6 +96,10 @@ class Notifier(object): ...@@ -73,6 +96,10 @@ class Notifier(object):
# in the dictionary. # in the dictionary.
if callback is None: if callback is None:
return return
# No more listeners for this topic
if len(listeners) == 0:
self.__listeners.pop(topic)
callback = callback.function() callback = callback.function()
...@@ -81,17 +108,33 @@ class Notifier(object): ...@@ -81,17 +108,33 @@ class Notifier(object):
else: else:
cbName = '<deleted>' cbName = '<deleted>'
log.debug('{}: De-registered listener {} (function: {})'.format( log.debug('{}: De-registered listener {} '
type(self).__name__, name, cbName)) '[topic: {}] (function: {})'.format(
type(self).__name__,
name,
topic,
cbName))
def notify(self, *args, **kwargs): def notify(self, *args, **kwargs):
"""Notify all registered listeners of this ``Notifier``. """Notify all registered listeners of this ``Notifier``.
All arguments passed to this method are ignored.
:args notifier_topic: Must be passed as a keyword argument.
The topic on which to notify. Default
listeners are always notified, regardless
of the specified topic.
All other arguments passed to this method are ignored.
""" """
topic = kwargs.get('notifier_topic', DEFAULT_TOPIC)
listeners = [self.__listeners[topic]]
listeners = list(self.__listeners.items()) if topic != DEFAULT_TOPIC:
listeners.append(self.__listeners[DEFAULT_TOPIC])
if sum(map(len, listeners)) == 0:
return
if log.getEffectiveLevel() >= logging.DEBUG: if log.getEffectiveLevel() >= logging.DEBUG:
stack = inspect.stack() stack = inspect.stack()
...@@ -100,22 +143,24 @@ class Notifier(object): ...@@ -100,22 +143,24 @@ class Notifier(object):
srcMod = '...{}'.format(frame[1][-20:]) srcMod = '...{}'.format(frame[1][-20:])
srcLine = frame[2] srcLine = frame[2]
log.debug('{}: Notifying {} listeners [{}:{}]'.format( log.debug('{}: Notifying {} listeners (topic: {}) [{}:{}]'.format(
type(self).__name__, type(self).__name__,
len(listeners), sum(map(len, listeners)),
topic,
srcMod, srcMod,
srcLine)) srcLine))
for ldict in listeners:
for name, callback in list(ldict.items()):
for name, callback in listeners: callback = callback.function()
callback = callback.function() # The callback, or the owner of the
# callback function may have been
# The callback, or the owner of the # gc'd - remove it if this is the case.
# callback function may have been if callback is None:
# gc'd - remove it if this is the case. log.debug('Listener {} has been gc\'d - '
if callback is None: 'removing from list'.format(name))
log.debug('Listener {} has been gc\'d - ' ldict.pop(name)
'removing from list'.format(name)) else:
self.__listeners.pop(name) callback(self)
else:
callback(self)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment