且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-08 22:32:22

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

When you write eval(whatever) in your code, eval is looked up by an ordinary global variable lookup. You should look for an ast.Name node representing a use of the variable name eval:

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

由于您有一个实际的函数对象,而不仅仅是源代码,因此,与仅拥有函数源的情况相比,您还可以检查以更可靠的方式遮盖内置变量的变量:

Since you have an actual function object, not just the source code, you can also check for variables that shadow the built-in in a slightly more reliable manner than if you just had the function's source:

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'))访问内置对象进行任何操作.值得吗?

This won't catch globals added after the check, and it won't do anything about accesses to the built-in by a different name (for example, x = eval; x('whatever')). Whether it's worthwhile is up to you.