Skip to main content
 首页 » 编程设计

python之在源代码中查找对 bool 值的隐式强制转换

2024年10月01日19mfryf

如何在源代码中找到所有对 bool 值的隐式转换?这包括像 if x 这样的条件语句,像 while x 这样的循环,像 x or y 这样的操作符,等等;但不是 if x == 0 或 if len(x) == 0 等。我不介意使用静态分析器、IDE 或正则表达式,或为此目的设计的 python 库。当然会有一些误报,当 x 实际上是 bool 值时;没关系。

用例:我发现了由强制转换为 bool 值引起的错误。例如,变量 x 应该是整数或 None 并且被错误地测试为 if not x 暗示 if x is无。我想使所有 bool 转换显式(例如,将 if not x 替换为 if x is None 或 if x == 0 等。 ).当然,它必须手动完成,但至少识别隐式转换发生的位置会有所帮助。

请您参考如下方法:

我建议您看一下标准的 ast 模块。这是一些简单的代码:

import ast 
source = ''' 
x=1 
if not x: 
    print('not x') 
''' 
 
tree = ast.parse(source) 
print(ast.dump(tree)) 

这是输出:

$ python test.py 
Module(body=[Assign(targets=[Name(id='x', ctx=Store())], value=Num(n=1)), If(test=UnaryOp(op=Not(), operand=Name(id='x', ctx=Load())), body=[Expr(value=Call(func=Name(id='print', ctx=Load()), args=[Str(s='not x')], keywords=[]))], orelse=[])]) 

Eli Bendersky 写了一篇 article关于使用 AST,他包含了一些示例代码,用于访问 AST 的节点。你会想去你寻找特定建筑的地方参观。在上面的示例中,您将在 If 节点下寻找(子)表达式,其中操作数被直接视为 bool 值,或被视为 Not( ) 节点。

找出所有可能的情况可能非常复杂。但我认为您可以使用一两页代码轻松找到“简单”情况(如果 x,如果不是 x,如果 x 或 y)。

编辑:这里有一些代码(我认为)可以满足您的需求。

import ast 
source = '''#Line 1 
x=1 
y=2 
 
if not x: 
    print('not x') 
 
if y is None: 
    print('y is none') 
 
 
while y or not x or (x < 1 and not y and x < 10): 
    print('x < 10') 
    x += 1 
 
''' 
 
tree = ast.parse(source) 
 
class FindNameAsBoolean(ast.NodeVisitor): 
    def __init__(self, lines): 
        self.source_lines = lines 
 
    def report_find(self, kind, locn, size=3): 
        print("\nFound %s at %s" % (kind, locn)) 
        print(self.source_lines[locn[0]-1]) 
        print(' ' * locn[1], '^' * size, sep='') 
 
    def visit_UnaryOp(self, node): 
        if isinstance(node.op, ast.Not) and isinstance(node.operand, ast.Name): 
            self.report_find('NOT-NAME', (node.lineno, node.col_offset), size=4 + len(node.operand.id)) 
        self.generic_visit(node) 
 
    def visit_BoolOp(self, node): 
        opname = type(node.op).__name__.upper() 
        for kid in node.values: 
            if isinstance(kid, ast.Name): 
                self.report_find('%s-NAME' % opname, (node.lineno, node.col_offset), size=len(kid.id)) 
 
        self.generic_visit(node) 
 
class FindTests(ast.NodeVisitor): 
    def __init__(self, lines): 
        self.source_lines = lines 
 
    def _fnab(self, node): 
        cond = node.test 
        FindNameAsBoolean(self.source_lines).visit(cond) 
 
    def visit_If(self, node): 
        self._fnab(node) 
        self.generic_visit(node) 
 
    def visit_While(self, node): 
        self._fnab(node) 
        self.generic_visit(node) 
 
FindTests(source.splitlines()).visit(tree) 

这是输出:

$ python test.py 
 
Found NOT-NAME at (5, 3) 
if not x: 
   ^^^^^ 
 
Found OR-NAME at (12, 6) 
while y or not x or (x < 1 and not y and x < 10): 
      ^ 
 
Found NOT-NAME at (12, 11) 
while y or not x or (x < 1 and not y and x < 10): 
           ^^^^^ 
 
Found NOT-NAME at (12, 31) 
while y or not x or (x < 1 and not y and x < 10): 
                               ^^^^^