Created
March 23, 2012 02:26
-
-
Save sirpengi/2166285 to your computer and use it in GitHub Desktop.
decorate everything!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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