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? :)

  • http://www.shanebauer.com/ Shane Bauer

    You don’t really need too much code in C#.

    this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);

  • http://www.shanebauer.com Shane Bauer

    You don’t really need too much code in C#.

    this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);

  • Zef

    That’s to subscribe, if you want to define one you first have to define a delegate and then a the event within a class itself. All you have to do here is: self.EvenName = Event()

  • Zef

    That’s to subscribe, if you want to define one you first have to define a delegate and then a the event within a class itself. All you have to do here is: self.EvenName = Event()

  • http://www.shanebauer.com/ Shane Bauer

    ah ok. Sorry, read your post wrong. I just woke up. Give me a break. ;)

  • http://www.shanebauer.com Shane Bauer

    ah ok. Sorry, read your post wrong. I just woke up. Give me a break. ;)

  • sunil

    The code didn’t worked for me.. do we need to do some changes in the code

  • sunil

    The code didn’t worked for me.. do we need to do some changes in the code