Yes, you can write a class decorator; The following allows you to decorate each of the class functions:
def decorate_all_functions(function_decorator): def decorator(cls): for name, obj in vars(cls).items(): if callable(obj): try: obj = obj.__func__
The above class decorator applies this function decorator to all called objects of the class.
Let's say you have a decorator that prints the name of the called function before and after:
from functools import wraps def print_on_call(func): @wraps(func) def wrapper(*args, **kw): print('{} called'.format(func.__name__)) try: res = func(*args, **kw) finally: print('{} finished'.format(func.__name__)) return res return wrapper
then the class decorator can be applied with:
@decorate_all_functions(print_on_call) class Foo: def func1(self): print('1') def func2(self): print('2')
Demo:
>>> @decorate_all_functions(print_on_call) ... class Foo: ... def func1(self): ... print('1') ... def func2(self): ... print('2') ... >>> c = Foo() >>> c.func1() func1 called 1 func1 finished >>> c.func2() func2 called 2 func2 finished
source share