I ran into unexpected results in a python if
clause today:
import numpy
if numpy.allclose(6.0, 6.1, rtol=0, atol=0.5):
print 'close enough' # works as expected (prints message)
if numpy.allclose(6.0, 6.1, rtol=0, atol=0.5) is True:
print 'close enough' # does NOT work as expected (prints nothing)
After some poking around (i.e., this question, and in particular this answer), I understand the cause: the type
returned by numpy.allclose()
is numpy.bool_
rather than plain old bool
, and apparently if foo = numpy.bool_(1)
, then if foo
will evaluate to True
while if foo is True
will evaluate to False
. This appears to be the work of the is
operator.
My questions are: why does numpy have its own boolean type, and what is best practice in light of this situation? I can get away with writing if foo:
to get expected behavior in the example above, but I like the more stringent if foo is True:
because it excludes things like 2
and [2]
from returning True
, and sometimes the explicit type check is desirable.