PEP8 E712要求“比较True应为if cond is True:或if cond:”。
PEP8 E712
True
if cond is True:
if cond:
但是,如果我遵循此规则,则会PEP8得到不同/错误的结果。为什么?
PEP8
In [1]: from pylab import * In [2]: a = array([True, True, False]) In [3]: where(a == True) Out[3]: (array([0, 1]),) # correct results with PEP violation In [4]: where(a is True) Out[4]: (array([], dtype=int64),) # wrong results without PEP violation In [5]: where(a) Out[5]: (array([0, 1]),) # correct results without PEP violation, but not as clear as the first two imho. "Where what?"
该建议仅适用于if测试值的“真实性”的语句。numpy是另一种野兽。
if
numpy
>>> a = np.array([True, False]) >>> a == True array([ True, False], dtype=bool) >>> a is True False
请注意,这a is True始终False是因为a是数组而不是布尔值,并且is执行简单的引用相等性测试(例如,仅True is True;None is not True例如)。
a is True
False
a
is
True is True
None is not True