Add an ObservableService class based on gPodder's
[panucci.git] / src / panucci / services.py
blob2c417b8b0ad6451edc30fb6432a04590578b404b
1 #!/usr/bin/env python
3 # from services.py -- Core Services for gPodder
4 # Thomas Perl <thp@perli.net> 2007-08-24
6 # 2009-02-13 - nikosapi: made ObservableService more Panucci-esque
9 from logging import getLogger
11 class ObservableService(object):
12 def __init__(self, signal_names=[], log=None):
13 self.__log = getLogger('ObservableService') if log is None else log
15 self.observers = {}
16 for signal in signal_names:
17 self.observers[signal] = []
19 if not signal_names:
20 self.__log.warning('No signal names defined...')
22 def register(self, signal_name, observer):
23 if signal_name in self.observers:
24 if not observer in self.observers[signal_name]:
25 self.observers[signal_name].append(observer)
26 self.__log.debug( 'Registered "%s" as an observer for "%s"',
27 observer.__name__, signal_name )
28 else:
29 self.__log.warning(
30 'Observer "%s" is already added to signal "%s"',
31 observer.__name__, signal_name )
32 else:
33 self.__log.warning(
34 'Signal "%s" is not available for registration', signal_name )
36 def unregister(self, signal_name, observer):
37 if signal_name in self.observers:
38 if observer in self.observers[signal_name]:
39 self.observers[signal_name].remove(observer)
40 self.__log.debug( 'Unregistered "%s" as an observer for "%s"',
41 observer.__name__, signal_name )
42 else:
43 self.__log.warning(
44 'Observer "%s" could not be removed from signal "%s"',
45 observer.__name__, signal_name )
46 else:
47 self.__log.warning(
48 'Signal "%s" is not available for un-registration.',
49 signal_name )
51 def notify(self, signal_name, *args, **kwargs):
52 caller = kwargs.get('caller')
53 caller = 'UnknownCaller' if caller is None else caller.__name__
55 if signal_name in self.observers:
56 self.__log.debug(
57 'Sending signal "%s" for caller "%s"', signal_name, caller )
59 for observer in self.observers[signal_name]:
60 observer( *args )
61 else:
62 self.__log.warning(
63 'Signal "%s" (from caller "%s") is not available '
64 'for notification', signal_name, caller )