Skip to main content

Posts

Showing posts from 2019

C#-like Events in Python

I've been experimenting with Python recently for a few different reasons: It's fun to learn new things I'm planning to build a site for a friend on top of Django and Wagtail I have some ideas for Kodi Addons I had the need to implement an observer pattern for decoupled publish/subscribe messaging between independent Python modules. C# has this built in to the language with events. I found  this Stack Overflow post where user  Jason Orendorff 's  answer provided the following excellent decorator: This is difficult at first to understand as a Python noob, but once you get it you appreciate the simplicity and the power the language has. Starting at the bottom, the boundevent class stores the event handlers and iterates over them when the function is invoked (i.e., the event is 'raised'). The event decorator exposes the boundevent (that is stored on the object instance) for a given event (which is really just a method) when it is accessed via the '...