Skip to content

Instantly share code, notes, and snippets.

Created August 26, 2011 01:27
Show Gist options
  • Save devdave/1172478 to your computer and use it in GitHub Desktop.
Save devdave/1172478 to your computer and use it in GitHub Desktop.
Proof of concept for tying a metaclass auto-decorator with a service bus
from collections import defaultdict
from functools import wraps
decoratedCalls = defaultdict(list)
def call(name, *args, **kwargs):
print name, args, kwargs
if name in decoratedCalls:
for cb in decoratedCalls[name]:
cb(*args, **kwargs)
class Subscribe(object):
def __init__(self, name): = name
def __call__(self, f):
return f
class BusDecorator(object):
def __init__(self, name): = name
def __call__(self, f):
def decorator(inst, *args, **kwargs):
call("%s-pre" %, inst, args, kwargs)
retval = f(inst, *args, **kwargs)
call("%s-post" %, inst, retval)
return retval
return decorator
class BusWrap(type):
def __new__(mcs, clsname, bases, cdict):
dbg = 1
modName = cdict.get("__module__", "unknownclass")
for name in cdict.keys():
prefix = "%s.%s.%s" % ( modName, clsname, name)
if callable(cdict[name]):
cdict[name] = BusDecorator(prefix)(cdict[name])
return type.__new__(mcs, name, bases, cdict)
class Foo(object):
__metaclass__ = BusWrap
def __init__(self):
print "init'd"
def bar(self):
print "bar"
def blah(self):
print "blah"
def ich(self):
print "ich"
def ego(self):
print "lego"
def say(self, *args):
print "Saying ", args
def preBar(inst, *args, **kwargs):
if not hasattr(inst, "ext_info"):
inst.ext_info = "Here"
def postEgo(inst, *args, **kwargs):
if hasattr(inst, "ext_info"):
print "Extended info is ", inst.ext_info
x = Foo()
x.say("abba", "dabba")
dbg = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment