Reputation: 9301
If I have something like this :
class SomeClass(object):
@classmethod
@some_decorator
def foo(cls, **kwargs):
pass
@some_decorator
def bar(self, **kwargs):
pass
@staticmethod
@some_decorator
def bar(**kwargs):
pass
@some_decorator
def function_outside_class(**kwargs):
pass
How should I make that @some_decorator so that it will work on every type of function listed above? Basically for now I need that decorator to run some code after the method (close SQLAlchemy session). I had problems making any decorator work with methods that are allready decorated with @staticmethod
Upvotes: 0
Views: 121
Reputation: 601599
As long as you keep the decorators in the order given in your post, a straight-forward implementation of the decorator should just work fine:
def some_decorator(func):
@functools.wraps(func)
def decorated(*args, **kwargs):
res = func(*args, **kwargs)
# Your code here
return res
return decorated
Note that you cannot do e.g.
@some_decorator
@staticmethod
def bar(**kwargs):
pass
since a staticmethod
object itself is not callable.
Upvotes: 2