Skip to main content
 首页 » 编程设计

python之检查函数中是否使用了某些运算符

2025年05月04日13shihaiming

我想禁止在函数中使用某些运算符,例如,假设我想确保 ** 幂运算符未在以下函数中使用:

def pow(x, y): 
    return x ** y 

我已经使用 inspect.getsource 获取源代码并检查 "**" 是否在源代码中,但如果碰巧会错误地导致断言错误在其他地方的源代码中是 "**" 那么如何实际检查代码是否存在特定运算符?

请您参考如下方法:

如果你手头有 3.4,我个人会选择 Ashwini 的答案,但是,如果你需要更兼容一点并且不介意解析源代码,那么你可以使用 ast,例如:

import inspect 
import ast 
 
def pow(x, y): 
    return x ** y 
 
nodes = ast.walk(ast.parse(inspect.getsource(pow))) 
has_power = any(isinstance(node, ast.Pow) for node in nodes)