我正在创建一个测试,该测试应该检查函数是否包含 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/