PEP8 E712
requires that "comparison to True
should be if cond is True:
or if cond:
".
But if I follow this PEP8
I get different/wrong results. Why?
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?"
Numpy's 'True' is not the same 'True' as Python's 'True' and therefor
is
fails:Also, specifically, PEP 8 says DONT use 'is' or '==' for Booleans:
An empty numpy array does test falsey just as an empty Python list or empty dict does:
Unlike Python, a numpy array of a single falsey element does test falsey:
But you cannot use that logic with a numpy array with more than one element:
So the 'spirit' of PEP 8 with Numpy is probably to only test each element's truthiness:
Or use
any
:And be aware that this is not what you expect:
Since
np.where
is returning a nonempty tuple.That advice only applies to
if
statements testing for the "truthiness" of a value.numpy
is a different beast.Note that
a is True
is alwaysFalse
becausea
is an array, not a boolean, andis
does a simple reference equality test (so onlyTrue is True
;None is not True
for example).