Original story: How to get the method decorated in Python
In the original blog, I checked with the * inspect * module, but this is convenient with the * ast * module.
find_decorator.py
# -*- coding: utf-8 -*-
import ast
source = """
class Sample(object):
@foo_decorator2
@foo_decorator1
def foo(self):
pass
@bar_decorator
def bar(self):
pass
def baz(self):
pass
@hoge_decorator2
@hoge_decorator1
def hoge(x):
pass
def fuga(x):
pass
"""
class FindDecorator(ast.NodeVisitor):
def visit_FunctionDef(self, node):
decorators = node.decorator_list
if decorators:
print('decorated: {}'.format(node.name))
for name in decorators:
print('decorator: {}'.format(name.id))
print('-' * 32)
return node
FindDecorator().visit(ast.parse(source))
Like this.
$ python find_decorator.py
decorated: foo
decorator: foo_decorator2
decorator: foo_decorator1
--------------------------------
decorated: bar
decorator: bar_decorator
--------------------------------
decorated: hoge
decorator: hoge_decorator2
decorator: hoge_decorator1
--------------------------------
Postscript: I was also able to dynamically get the module source code using * inspect.getsource *.
3.4
# -*- coding: utf-8 -*-
import ast
import inspect
import sys
def foo_decorator2(func): pass
def foo_decorator1(func): pass
def bar_decorator(func): pass
def hoge_decorator2(func): pass
def hoge_decorator1(func): pass
class Sample(object):
@foo_decorator2
@foo_decorator1
def foo(self):
pass
@bar_decorator
def bar(self):
pass
def baz(self):
pass
@hoge_decorator2
@hoge_decorator1
def hoge(x):
pass
def fuga(x):
pass
class FindDecorator(ast.NodeVisitor):
def visit_FunctionDef(self, node):
decorators = node.decorator_list
if decorators:
print('decorated: {}'.format(node.name))
for name in decorators:
print('decorator: {}'.format(name.id))
print('-' * 32)
return node
module = sys.modules[__name__]
source = inspect.getsource(module)
FindDecorator().visit(ast.parse(source))
You can get the source code of the object passed in the argument of * inspect.getsource *. Here, the module itself is passed, but classes and functions can also be passed.
Recommended Posts