Skip to content

Instantly share code, notes, and snippets.

@jeroenpelgrims
Created August 27, 2010 19:58
Show Gist options
  • Save jeroenpelgrims/554076 to your computer and use it in GitHub Desktop.
Save jeroenpelgrims/554076 to your computer and use it in GitHub Desktop.
In relation to this blog post: http://blog.jeroenpelgrims.be/2010/08/using-c-style-events-in-python/ and the question posed in the comments. Would like some help improving the code.
class Event(object):
def __init__(self):
self.__handlers = []
def subscribe(self, handler):
self.__handlers.append(handler)
def unsubscribe(self, handler):
self.__handlers.remove(handler)
def __call__(self, *args):
for handler in self.__handlers:
handler(*args)
class Publisher(object):
def __init__(self):
self.notify = Event()
def trigger_notify(self):
self.notify("A", "B")
class Subscriber(object):
def start_listening_to(self, publisher):
self.__publisher = publisher
self.__publisher.notify.subscribe(self.event_handler)
def stop_listening(self):
self.__publisher.notify.unsubscribe(self.event_handler)
self.__publisher = None
def event_handler(self, param1, param2):
print "RECEIVED: param1: %s, param2: %s" % (param1, param2)
publisher = Publisher()
subscriber1 = Subscriber()
subscriber2 = Subscriber()
subscriber1.start_listening_to(publisher)
subscriber2.start_listening_to(publisher)
publisher.trigger_notify()
subscriber1.stop_listening()
publisher.trigger_notify()
'''
I removed the alteration of the object base class. It didn’t seem like the right thing to do, modifying an existing class.
Now the setting of an event attribute is a lot simpler, just say that attribute x is an event.
I liked the way of adding and removing events by using the += and -= operators, but it didn’t seem very intuitive to me and I’ve never seen them be used like that in Python so I changed it to regular methods.
The way arguments are passed to the handlers also changed, I used to pass an array of arguments when calling the event.
Now I just pass arguments like you would with any other function. Way more intuitive.
When subscribing I also don’t check whether the handler is callable anymore.
When triggering the event you’ll get an appropriate error message if the handler is in fact not callable.
The same happens when you pass a handler which has the incorrect amount of parameters.
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment