I tried "How to get a method decorated in Python"

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

I tried "How to get a method decorated in Python"
How to get a stacktrace in python
I tried to implement a pseudo pachislot in Python
I tried to summarize how to use pandas in python
I tried to implement a one-dimensional cellular automaton in Python
How to use the __call__ method in a Python class
How to get the last (last) value in a list in Python
How to get a list of built-in exceptions in python
I tried to make a stopwatch using tkinter in python
I tried to implement PLSA in Python
I tried to implement permutation in Python
I tried to implement PLSA in Python 2
I tried to implement ADALINE in Python
I tried to implement PPO in Python
[Python] A memo that I tried to get started with asyncio
How to get a string from a command line argument in python
I tried to implement a misunderstood prisoner's dilemma game in Python
I tried to create a Python script to get the value of a cell in Microsoft Excel
I tried to build a super-resolution method / ESPCN
How to clear tuples in a list (Python)
How to embed a variable in a python string
I tried to build a super-resolution method / SRCNN ①
I tried playing a typing game in Python
I tried the least squares method in Python
I tried to get CloudWatch data with Python
[Memo] I tried a pivot table in Python
I tried to implement TOPIC MODEL in Python
How to notify a Discord channel in Python
How to get the files in the [Python] folder
I tried adding a Python3 module in C
I tried to build a super-resolution method / SRCNN ③
[Python] How to draw a histogram in Matplotlib
I tried to build a super-resolution method / SRCNN ②
I tried to implement selection sort in python
How to get a value from a parameter store in lambda (using python)
I tried to develop a Formatter that outputs Python logs in JSON
I tried to implement a card game of playing cards in Python
How to develop in Python
I tried to graph the packages installed in Python
How to convert / restore a string with [] in python
I want to embed a variable in a Python string
How to get the variable name itself in python
I want to easily implement a timeout in python
How to get the number of digits in Python
I tried to summarize how to use matplotlib of python
I tried to get started with blender python script_Part 01
I tried to draw a route map with Python
I want to write in Python! (2) Let's write a test
[Python] How to expand variables in a character string
I tried to get started with blender python script_Part 02
I want to randomly sample a file in Python
I tried to implement Dragon Quest poker in Python
I want to work with a robot in python.
I tried to implement GA (genetic algorithm) in Python
I tried to automatically generate a password with Python3
[Python] Created a method to convert radix in 1 second
How to execute a command using subprocess in Python
[Python] I tried to get Json of squid ring 2
I tried to create a class that can easily serialize Json in Python
[Python] I tried to get the type name as a string from the type function
I tried to implement what seems to be a Windows snipping tool in Python