How to get all methods of a python class with given decorator

后端 未结 6 1975
天命终不由人
天命终不由人 2020-12-02 05:18

How to get all methods of a given class A that are decorated with the @decorator2?

class A():
    def method_a(self):
      pass

    @decorator1
    def met         


        
6条回答
  •  隐瞒了意图╮
    2020-12-02 05:55

    To expand upon @ninjagecko's excellent answer in Method 2: Source code parsing, you can use the ast module introduced in Python 2.6 to perform self-inspection as long as the inspect module has access to the source code.

    def findDecorators(target):
        import ast, inspect
        res = {}
        def visit_FunctionDef(node):
            res[node.name] = [ast.dump(e) for e in node.decorator_list]
    
        V = ast.NodeVisitor()
        V.visit_FunctionDef = visit_FunctionDef
        V.visit(compile(inspect.getsource(target), '?', 'exec', ast.PyCF_ONLY_AST))
        return res
    

    I added a slightly more complicated decorated method:

    @x.y.decorator2
    def method_d(self, t=5): pass
    

    Results:

    > findDecorators(A)
    {'method_a': [],
     'method_b': ["Name(id='decorator1', ctx=Load())"],
     'method_c': ["Name(id='decorator2', ctx=Load())"],
     'method_d': ["Attribute(value=Attribute(value=Name(id='x', ctx=Load()), attr='y', ctx=Load()), attr='decorator2', ctx=Load())"]}
    

提交回复
热议问题