python - 有没有办法让 python 函数知道它在模块加载时被装饰了?

标签 python python-decorators

举个例子:

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

@decorator
def decorated(): pass

有没有办法让 decorated 知道它正在被装饰?

最佳答案

你可以使用一个使用ast.NodeVistor的装饰器来遍历函数的AST节点来寻找函数的装饰器。如果装饰器列表包含的不仅仅是装饰器检查器本身,那么您可以从装饰器节点中获取其他装饰器的详细信息:

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

这样:

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

@decorator
@check_decorators
def decorated():
    pass

会输出:

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

关于python - 有没有办法让 python 函数知道它在模块加载时被装饰了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52941573/

相关文章:

python - 无法使用 Bootstrap 设置 Django 默认登录表单的样式

python - django装饰器中访问请求用户和url参数

python - 我可以在 Python 中为继承的方法创建别名吗?

Python 从一个文件中创建多个文件

python - 在 python 中跳过 for 循环中的迭代?

python - 授权 AWS Python Cognito 错误 : User pool client ******** does not exist

python - 在 Python 中为函数装饰器创建别名

python - 尝试将统计数据放入角色表中

python - 动态创建一个类而不实例化它 - 没有元类?

python - 是否可以检查一个函数是否在另一个函数内被修饰?