Skip to content

Instantly share code, notes, and snippets.

@Alexei-Kornienko
Created July 24, 2014 21:11
Show Gist options
  • Save Alexei-Kornienko/29d4209bbfe17f546797 to your computer and use it in GitHub Desktop.
Save Alexei-Kornienko/29d4209bbfe17f546797 to your computer and use it in GitHub Desktop.
python events
class Event(object):
def __init__(self):
self._callbacks = set()
def fire(self, *args, **kwargs):
for callback in self._callbacks:
try:
callback(*args, **kwargs)
except Exception:
LOG.exception('Error during event callback')
def __iadd__(self, callback):
if not callable(callback):
raise ValueError('Invalid callback registered')
self._callbacks.add(callback)
return self
def __isub__(self, callback):
self._callbacks.remove(callback)
return self
def message_handler(message):
print message
on_message = Event()
on_message += message_handler
on_message.fire('hello world')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment