Skip to content

Instantly share code, notes, and snippets.

@sirpengi
Created March 23, 2012 02:26
Show Gist options
  • Save sirpengi/2166285 to your computer and use it in GitHub Desktop.
Save sirpengi/2166285 to your computer and use it in GitHub Desktop.
decorate everything!
def DecorateEverything(decorator):
"""Function that returns a metaclass that decorates
all class callables (except those starting with __)
with `decorator`."""
class DEMeta(type):
def __init__(cls, name, bases, dct):
new_dct = {}
for k, v in dct.iteritems():
if hasattr(v, "__call__") and not k.startswith('__'):
setattr(cls, k, decorator(v))
return DEMeta
"""usage sample below:"""
class MyClass(object):
__metaclass__ = DecorateEverything(property)
foo_attr = "foo_attr"
def __init__(self, v):
self.v = v
def foo(self):
return "foo" + self.v
class MyOtherClass(object):
__metaclass__ = DecorateEverything(staticmethod)
foo_attr = "foo_attr"
def foo():
return "foo"
m = MyClass("bar")
print m.foo # foobar
print m.foo_attr # foo_attr
print MyOtherClass.foo() # foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment