Implementing C#/.NET events in Python

One of the things I liked in C# is its event-system. Although you need quite a lot of code to define an event. When I saw Python supports operator overload, I thought I’d try to implement such an event system in Python, and I did in 12 lines of code:

class Event:
def __init__(self):
self.listeners = []
def __call__(self, *params):
for l in self.listeners:
l(*params)
def __add__(self, listener):
self.listeners.append(listener)
return self
def __sub__(self, listener):
self.listeners.remove(listener)
return self

This is how you can use it:

class MyClass:
def __init__(self):
self.Clicked = Event()
def click(self, button):
self.Clicked(self, button)
def onClick(sender, button):
print 'Button clicked: %s' % button
o = MyClass()
o.Clicked += onClick # subscribe to event
o.click('Right') # Trigger the event from outside
Cool huh? :)