Python 3.x : how to use ast to search for a print statement

标签 python python-3.x module abstract-syntax-tree

我正在创建一个测试,该测试应该检查函数是否包含 print 语句(Python 3.x,我使用的是 3.7.4)。我一直在使用 ast 检查类似的事情(引用 this 问题中的答案),例如 return 或列表理解,但我陷入困境打印

online AST explorer在正文中列出了一个 Print 子类,并且它使用 Python 3 print,所以我知道它不是 Python 2 的东西。

Green Tree Snakes ast 文档说 Print 在 Python 2 中只有一个 ast 节点。这更接近我所经历的。这是我将用来做出断言的函数:

def printsSomething(func):
    return any(isinstance(node, ast.Print) for node in ast.walk(ast.parse(inspect.getsource(func))))

返回:

TypeError: isinstance() arg 2 must be a type or tuple of types

我假设这与 print 作为 Python 3.x 中的一个函数有关,但我不知道如何利用这些知识来发挥我的优势。我如何使用 ast 来查明 print 是否已被调用?

我想重申一下,我已经让这段代码适用于其他 ast 节点,例如 return,所以我应该确信这不是我的代码特有的错误。

谢谢!

最佳答案

如果调用任何命名对象(包括诸如print之类的函数),那么您的节点中将至少有一个_ast.Name对象>s。对象的名称(“print”)存储在该节点的 id 属性下。

我相信您已经知道,print 在 python 版本 2 和 3 之间从语句更改为函数,这可能解释了您遇到问题的原因。

尝试以下操作:

import ast
import inspect

def do_print():
    print('hello')

def dont_print():
    pass

def prints_something(func):
    is_print = False
    for node in ast.walk(ast.parse(inspect.getsource(func))):
        try:
            is_print = (node.id == 'print')
        except AttributeError:  # only expect id to exist for Name objs
            pass
        if is_print:
            break
    return is_print

prints_something(do_print), prints_something(dont_print)

>>> True, False

...或者如果您喜欢单行代码(其中 func 是您要测试的函数):

any(hasattr(node,'id') and node.id == 'print' 
    for node in ast.walk(ast.parse(inspect.getsource(func))))

关于Python 3.x : how to use ast to search for a print statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57806591/

相关文章:

python - Mac os x 10.8 : Fatal Python error: PyThreadState_Get: no current thread importing mapnik 上的 Homebrew + Python

linux - 如何远程关闭基于 Linux 的计算机?

python - 在 Python 中解析句子(或其他更长的字符串)(ProblemSetQuestion)如何进行?

python - 如何使用python动态地将方法导出到dbus,而不需要静态装饰器?

python - 如何在 Python 中使用 Selenium 提取文本元素?

python - 将我的解决方案改进为 PE 21?

amazon-web-services - 如何将现有库作为模块导入 Go 1.11?

java - 从Android应用程序中的其他模块引用公共(public)模块

python - 在 sqlalchemy 中触发

python - 我如何轻松地从斯坦福大学解析 python 中的数据绘制解析树?