Python ProgrammingPython Programming

How to get all methods of a Python class with given decorator?

import inspect


def deco(func):
    return func


def deco2():
    def wrapper(func):
        pass
    return wrapper


class Test(object):
    @deco
    def method(self):
        pass

    @deco2()
    def method2(self):
        pass


def methodsWithDecorator(cls, decoratorName):
    sourcelines = inspect.getsourcelines(cls)[0]
    for i, line in enumerate(sourcelines):
        line = line.strip()
        if line.split('(')[0].strip() == '@' + decoratorName:  # leaving a bit out
            nextLine = sourcelines[i + 1]
            name = nextLine.split('def')[1].split('(')[0].strip()
            yield(name)


print(list(methodsWithDecorator(Test, 'deco')))
print(list(methodsWithDecorator(Test, 'deco2')))
Output
['method']
['method2']