Reputation: 855
Can someone explain the logic behind the output of the following script?
import numpy
if(numpy.dtype(numpy.float64):
print "Expected"
else:
print "Surprise!!!!"
Especially considering:
import numpy
if(object):
print "Expected!"
else:
print "Surprise"
Thanks :)
Upvotes: 1
Views: 670
Reputation: 249113
np.dtype
does not define __nonzero__
, but it does define __len__
. As per the documentation, this means when you use it in a boolean context, it will evaluate to True if __len__
returns non-zero. But it always returns zero, regardless of what type you pass in:
>>> bool(np.dtype(int))
False
>>> bool(np.dtype(float))
False
>>> bool(np.dtype(np.int8))
False
On the other hand, a compound data type does return nonzero, thus True:
>>> bool(np.dtype([('foo', int)]))
True
You might then ask why the "length" of a simple dtype is zero, when the length of a compound one with a single element is one. I imagine that's something about dimensionality: an array with a simple dtype and one-dimensional size is itself one-dimensional, but an array with a compound dtype and one-dimensional size may be thought of as two-dimensional, regardless of how many elements are in the compound dtype.
Upvotes: 3