Created
July 24, 2014 21:11
-
-
Save Alexei-Kornienko/29d4209bbfe17f546797 to your computer and use it in GitHub Desktop.
python events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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