Python – Is there a way to let the python function know it’s decorated when the module loads?

Is there a way to let the python function know it’s decorated when the module loads?… here is a solution to the problem.

Is there a way to let the python function know it’s decorated when the module loads?

For example:

def decorator(func): 
    def nested(*args, **kwargs):
        return func(*args, **kwargs)
    return nested

@decorator
def decorated(): pass

Is there a way to let decorated know it’s being decorated?

Solution

You can use one using an ast. NodeVistor's decorator iterates through the function’s AST node to find the function’s decorator. If the decorator list contains more than just the decorator inspector itself, you can get the details of other decorators from the decorator node:

import inspect
import ast
from textwrap import dedent

class CheckDecorators(ast. NodeVisitor):
    def visit_FunctionDef(self, node):
        if len(node.decorator_list) > 1:
            print("function '%s' is decorated by: %s" % (node.name, ', '.join(ast.dump(decorator) for decorator in node.decorator_list if not isinstance(decorator, ast. Name) or decorator.id != 'check_decorators')))

def check_decorators(func):
    CheckDecorators().visit(ast.parse(dedent(inspect.getsource(func))))
    return func

This way:

def decorator(func):
    def nested(*args, **kwargs):
        return func(*args, **kwargs)
    return nested

@decorator
@check_decorators
def decorated():
    pass

Will output:

function 'decorated' is decorated by: Name(id='decorator', ctx=Load())

Related Problems and Solutions