1

I have this class method decorator from https://stackoverflow.com/a/46361833/5316326 that accepts parameters.

How can I list the class methods that use this decorator on the created object?

from functools import update_wrapper, partial

def my_decorator(name):
    class MyDecorator(object):
        def __init__(self, func):
            update_wrapper(self, func)
            self.func = func

        def __get__(self, obj, objtype):
            """Support instance methods."""
            return partial(self.__call__, obj)

        def __call__(self, obj, *args, **kwargs):
            return self.func(obj, *args, **kwargs)

    return MyDecorator

class MyClass(object):

    t=12
    
    @my_decorator("hee")
    def my_method(self, a):
        print(a+self.t)

The following attempt works, but by parsing the partial function to a string, there should be a correct implementation:

def find_my_decorators(cls):
    def g():
        for name in dir(cls):
            attr = getattr(cls, name)
            if isinstance(attr, partial) and 'MyDecorator' in str(attr.func):
                yield name

    return [name for name in g()]

It gives, however, the desired results:

>>> find_my_decorators(MyClass)
['my_method']
>>> m = MyClass()
>>> m.my_method(a=12)
>>> find_my_decorators(m)
['my_method']

It works both on the class as the object.

Joost Döbken
  • 3,450
  • 2
  • 35
  • 79

0 Answers0