一尘不染

与布尔numpy数组VS PEP8 E712的比较

python

PEP8 E712要求“比较True应为if cond is True:if cond:”。

但是,如果我遵循此规则,则会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?"

阅读 135

收藏
2021-01-20

共1个答案

一尘不染

该建议仅适用于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 TrueNone is not True例如)。

2021-01-20