aepsil0n/obsub — pull request #43 by DanielSank (2014-02-21 06:44:36+00:00)
Title: Added EventMetaclass

Suppose you have a class Foo which has a method .bar to which you'd like to apply the @event decorator, but that class is defined externally to your project. You're stuck subclassing Foo and re-implementing .bar with manual addition of the @event decorator. That's ok for some cases, but it's kind of ugly and can be really tedious.

In this submission I introduce a metaclass so that the @event decorator can be applied to specified methods _at class construction time_. A full explanation with a working example are given in the docstring of obsub.EventMetaclass, but here's the basic idea

class Foo(object):
def bar(self, arg):
print("bar called with argument %s"%(arg,))

class MySubclass(Foo):
__metaclass__ = obsub.EventMetaclass
_event_methods = ['bar']

def callback(obj, arg):
print("callback fired with argument %s"%(arg,))

f = MySubclass()
f.bar += callback
f.bar('baz')
> bar called with argument baz
> callback fired with argument baz