Attaching a decorator to all functions within a class

The cleanest way to do this, or to do other modifications to a class definition, is to define a metaclass.

Alternatively, just apply your decorator at the end of the class definition using inspect:

import inspect

class Something:
    def foo(self): 
        pass

for name, fn in inspect.getmembers(Something, inspect.isfunction):
    setattr(Something, name, decorator(fn))

In practice of course you’ll want to apply your decorator more selectively. As soon as you want to decorate all but one method you’ll discover that it is easier and more flexible just to use the decorator syntax in the traditional way.

Leave a Comment