Skip to content

Instantly share code, notes, and snippets.

@Xorcerer
Created April 11, 2014 07:58
Show Gist options
  • Save Xorcerer/10448309 to your computer and use it in GitHub Desktop.
Save Xorcerer/10448309 to your computer and use it in GitHub Desktop.
A event implementation like boost::signal or C# event.
class AggregateException(Exception):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.sub_exceptions = []
def add(self, exception):
self.sub_exceptions.append(exception)
@property
def message(self):
return '\n'.join([e.message for e in self.sub_exceptions])
def __nonzero__(self):
return bool(self.sub_exceptions)
class Event(object):
def __init__(self, *param_type_list, **kwargs):
'param_type_list is optional, elide to disable parameter types check.'
self.callbacks = []
self.param_type_list = param_type_list
self.continue_on_exception = kwargs.get('continue_on_exception', False)
def __call__(self, *args, **kwargs):
'Check then call.'
if self.param_type_list:
for i, a in enumerate(args, start=1):
t = self.param_type_list[i - 1]
if not isinstance(a, t):
raise ValueError('Error parameter type at %d, '
'value %s, should be %s.' % (i, a, t))
exception_set = AggregateException()
for c in self.callbacks:
try:
c(*args, **kwargs)
except Exception as e:
if not self.continue_on_exception:
raise
exception_set.add(e)
if exception_set:
raise exception_set
def add(self, callback):
self.callbacks.append(callback)
def remove(self, callback):
self.callbacks.remove(callback)
# <-- Line 52 Here. Sorry, Sam.
def ____________________________():
print '-' * 32
def test():
def say_hi(name, greeting_msg):
print 'Hi, %s.' % name
def echo(name, greeting_msg):
print '%s said, %s.' % (name, greeting_msg)
def bad_func(name, greeting_msg):
raise Exception('I am bad.')
on_greeting = Event(str, str)
on_greeting.add(say_hi)
on_greeting.add(echo)
on_greeting('Logan', 'Hello')
____________________________()
on_greeting = Event(str, str, continue_on_exception=True)
on_greeting.add(say_hi)
on_greeting.add(bad_func)
on_greeting.add(echo)
on_greeting('Sam', 'Hi')
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment