Saša Šijak
Saša Šijak

Reputation: 9301

How to use the same python decorator for all types of methods/functions?

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

Answers (1)

Sven Marnach
Sven Marnach

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

Related Questions