Skip to content

Instantly share code, notes, and snippets.

@jrdmcgr
Last active December 17, 2015 16:09
Show Gist options
  • Save jrdmcgr/5636878 to your computer and use it in GitHub Desktop.
Save jrdmcgr/5636878 to your computer and use it in GitHub Desktop.
from types import MethodType
from functools import wraps
def decorate_methods(decorator):
"""
Return a class decorator that will decorate public methods with the given decorator.
"""
def class_decorator(klass):
for name in dir(klass):
if name.startswith('_'):
continue
attr = getattr(klass, name)
if isinstance(attr, MethodType):
fn = decorator(attr)
setattr(klass, name, fn)
return klass
return class_decorator
# Test it out.
def say_your_name(fn):
@wraps(fn)
def wrapper(*args, **kw):
print 'Hi, my name is %s' % fn.__name__
return fn(*args, **kw)
return wrapper
@decorate_methods(say_your_name)
class Test(object):
def foo(self):
pass
def bar(self):
pass
def baz(self):
pass
t = Test()
t.foo()
# Hi, my name is foo
t.bar()
# Hi, my name is bar
t.baz()
# Hi, my name is baz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment