[Numpy-discussion] "False" and "True" not singletons?
josef.pktd@gmai...
josef.pktd@gmai...
Tue Dec 30 15:22:26 CST 2008
On Tue, Dec 30, 2008 at 2:59 PM, Christopher Barker
<Chris.Barker@noaa.gov> wrote:
> Hi all,
>
> I've just discovered that "False" is not a singleton:
>
> >>> import numpy as N
>
> >>> f = N.all((1,2,0))
> >>> print f
> False
> >>> id(f)
> 17316364
> >>> f is False
> False
> >>> id(False)
> 3294768
>
>
> Should it be?
>
>
> This arose for me in some tests I'm using that check if a result is False:
>
> self.failUnless ( (self.B1 == self.B3) is False )
>
> I'm doing it this way, because I want to make sure that the __eq__
> method really is returning "True" or "False", rather than a value that
> happens to evaluate to true or false, like 1, or an empty list, or whatever.
>
> This is interesting to me because back when Python first introduced
> Booleans, I had thought they should be kept pure and not be subclasses
> of integers, and, in fact, "if" should only except boolean values.
> However this opinion was really a matter of my sense of purity, and this
> is the fist time I've run into a case that matters.
>
> I suppose I'm not being pythonic -- I should really only care if the
> result evaluates true or false, but I don't feel like I'm testing right
> if values can slip though that shouldn't.
>
> It does reinforce my opinion though -- whether zero, or an empty
> sequence or string should evaluate false really is a matter of specific
> application, not universal.
>
> Anyway, should I just give up? Or should numpy return the same "True"
> and "False" (like None), or is there another solution?
>
> x == False
>
> is close, but zero still slips through, even though an empty list does not:
>
> >>> 0 == False
> True
> >>> [] == False
> False
>
>
> -Chris
>
>
> --
> Christopher Barker, Ph.D.
> Oceanographer
>
> Emergency Response Division
> NOAA/NOS/OR&R (206) 526-6959 voice
> 7600 Sand Point Way NE (206) 526-6329 fax
> Seattle, WA 98115 (206) 526-6317 main reception
>
> Chris.Barker@noaa.gov
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
If you really insist on getting a boolean type, then you can check
with isinstance:
>>> if not np.any(np.ones(3)==0) and isinstance(np.any(np.ones(3)==0),np.bool_):print 'ok'
ok
>>> if not (1==0) and isinstance((1==0),bool):print 'ok'
ok
>>> f = np.all((1,2,0))
>>> if not f and isinstance(f,np.bool_):print 'ok'
ok
zero is not an instance of boolean:
>>> f=0
>>> if not f and isinstance(f,np.bool_):print 'ok'
>>> if not f and isinstance(f,bool):print 'ok'
>>>
Josef
More information about the Numpy-discussion
mailing list