Search code examples
pythonfunctionclasspython-decorators

How to get a class of a method?


I created a decorator for a method in my class, but inside the decorator, I need to get the class of the method. How can I do that?

Here is the code of what I am trying to do:


def my_decorator(method):
    a = # The class of "method"
    print(a)  # <class '__main__.MyClass'>

class MyClass:
    @my_decorator
    def my_method(self, *args, **kwargs):
        ...

Solution

  • First you need to fix the decorator... you get the reference of the class as the first argument passed to the __wrapper. To get the parameter identifier you can use a code object and then use it as the key of locals.

    Notice that this method is sensible on the signature of the decorator. In this case the last [0] is needed only because the first argument is *args,a tuple, and the first entry is needed.

    def my_decorator(method):
        def __wrapper(*args, **kwargs):
            cls = locals()[__wrapper.__code__.co_varnames[0]][0]
    
            print(type(cls))
            print(hasattr(cls, method.__name__))
            return method(*args, **kwargs)
        return __wrapper
    
    
    class MyClass:
        @my_decorator
        def my_method(self, *args, **kwargs):
            pass
    
    
    MyClass().my_method()
    

    Output

    <class '__main__.MyClass'>
    True