Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有以下python代码
a = 2 if a == 1: b = 'blah' print b else: print b
当我尝试运行它时,我得到一个运行时错误,因为“b”只在“if”子句中定义,而不是“else”。
Pylint 和 Pyflakes 都未能检测到这个问题。
有没有其他方法可以在不运行代码的情况下检测到它?
我认为如果不运行代码就无法检测到这一点,因为一般来说,工作中的逻辑可能比您的示例更复杂。如果一个循环多次迭代这个if-else子句,并且由于某种原因你确定第一次b肯定会被分配,那又如何呢?检查器需要与解释器一样复杂(并执行类似的操作,可能包括副作用)才能了解程序运行的所有可能状态。请参阅静态代码检查的概念。
if
else
b