When comparing numpy.all() of a boolean array of True
values using the is
operator I get an unexpected False
as output. However I get the expected outcome (True
) when using the ==
operator. What is the likely reason for this comparison failure?
A sample code is attached below.
In[2]: import sys
In[3]: print(sys.version)
3.9.5
In[4]: import numpy as np
In[5]: np.__version__
'1.20.3'
In[6]: bool1 = True
In[7]: bool1 is True
True
In[8]: bool1 == True
True
In[9]: bool_arr = np.array([True, True, True, True])
In[10]: bool_arr.all()
True
In[11]: bool_arr.all() == True
True
In[12]: bool_arr.all() is True
False
As can be observed from the above code, in input 12, the expected outcome is True
but the actual outcome is False
.
I'm using pyenv in Ubuntu as the environment for python.
EDIT: as suggested in comments, this is not the best practice of using python. However, I'm interested to know the root cause for this failure.
CodePudding user response:
If you inspect the type of bool_arr.all()
, the answer will be immediately apparent:
>>> bool_arr.all()
<class 'numpy.bool_'>
np.all
returns an instance of a numpy bool_
, which is a different class than python's built-in bool
type. Instances of different types can not be the same object, which is what is
is telling you.
The correct way to check truthiness is to let python wrap an expression in bool
for you, e.g., in an if
statement like if bool_arr.all():
.