Reputation: 875
I would like to apply a decorator to all methods of a class programmatically. With a condition that if a certain decorator already exists, skip adding the decorator to that method.
I have something like this code, but I can't figure out the API that would tell me what other decorators may already exist on the method. In my case I want to skip adding cacheable
decorator for certain methods which have the non_cacheable
decorator on them
def cacheable():
def decorate(cls):
for name, fn in inspect.getmembers(cls, inspect.ismethod):
setattr(cls, name, decorator(fn))
return cls
return decorate
@cacheable
class C(object):
@not_cacheable
def method_1(self): pass
def method_2(self, x): pass
...
Upvotes: 0
Views: 133
Reputation: 26954
Try adding an attribute:
def not_cachable(func):
func._cache = False
return func
Then check the attribute in your cacheable
decorator.
That's how many of the functions in the standard library work, for example @abstractmethod
.
Upvotes: 1