gpt4 book ai didi

python - 如何查找/检测 Python AST 中是否使用了内置函数?

转载 作者:行者123 更新时间:2023-12-05 06:42:25 26 4
gpt4 key购买 nike

目标是检测是否在某些代码中使用了内置函数,例如 eval()

def foo(a):
eval('a = 2')

我尝试了以下方法:

ex_ast = ast.parse(inspect.getsource(foo))

for node in ast.walk(ex_ast):
if isinstance(node, ast.FunctionDef):
print(node.name)

函数名称 foo 被打印为输出。

我知道内置函数没有构造函数。它们在 type 模块中。因此,一种方法是在 isinstance 调用中使用 types.FunctionType

但是因为我使用的是 AST 节点。它们无法转换回代码。我必须检查每个节点是否为 types.FunctionType:

for node in ast.walk(ex_ast):
if isinstance(node, ast.FunctionType):
print(node.name)

我遇到了这些错误:

AttributeError: module 'ast' has no attribute 'FunctionType'

我应该如何正确识别代码中是否使用了特定的内置函数?谢谢!

最佳答案

当您在代码中编写 eval(whatever) 时,eval 会通过普通的全局变量查找进行查找。您应该寻找一个 ast.Name 节点来表示变量名称 eval 的使用:

for node in ast.walk(ex_ast):
if isinstance(node, ast.Name) and node.id == 'eval':
# Found it.

因为你有一个实际的函数对象,而不仅仅是源代码,你还可以检查隐藏内置函数的变量,这种方式比你只有函数的源代码更可靠:

if ('eval' in foo.__code__.co_varnames     # local variable
or 'eval' in foo.__code__.co_cellvars # local variable used by nested function
or 'eval' in foo.__code__.co_freevars # local variable from enclosing function
or 'eval' in foo.__globals__): # global variable
# Some variable is shadowing the built-in.

这不会捕获检查后添加的全局变量,并且不会对通过不同名称访问内置变量做任何事情(例如,x = eval; x('whatever'))。是否值得取决于您。

关于python - 如何查找/检测 Python AST 中是否使用了内置函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37217823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com