1 """The Observable class for decoupled notifications"""
2 from __future__
import absolute_import
, division
, print_function
, unicode_literals
5 class Observable(object):
6 """Handles subject/observer notifications."""
9 self
.notification_enabled
= True
12 def add_observer(self
, message
, observer
):
13 """Add an observer for a specific message."""
14 observers
= self
.observers
.setdefault(message
, set())
15 observers
.add(observer
)
17 def remove_observer(self
, observer
):
18 """Remove an observer."""
19 for _
, observers
in self
.observers
.items():
20 if observer
in observers
:
21 observers
.remove(observer
)
23 def notify_observers(self
, message
, *args
, **opts
):
24 """Pythonic signals and slots."""
25 if not self
.notification_enabled
:
27 # observers can remove themselves during their callback so grab a copy
28 observers
= set(self
.observers
.get(message
, set()))
29 for method
in observers
: