Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python things which are neither True nor False

Tags:

python

boolean

I just found this :

a = (None,)
print (a is True)
print (a is False)
print (a == True)
print (a == False)
print (a == None)
print (a is None)
if a : print "hello"
if not a : print "goodbye"

which produces :

False
False
False
False
False
False
hello

So a neither is, nor equals True nor False, but acts as True in an if statement.

Why?

Update :

actually, I've just realized that this isn't as obscure as I thought. I get the same result for a=2, as well (though not for a=0 or a=1, which are considered equal to False and True respectively)

like image 650
interstar Avatar asked Oct 18 '09 12:10

interstar


2 Answers

I find almost all the explanations here unhelpful, so here is another try:

The confusion here is based on that testing with "is", "==" and "if" are three different things.

  • "is" tests identity, that is, if it's the same object. That is obviously not true in this case.
  • "==" tests value equality, and obviously the only built in objects with the values of True and False are the object True and False (with the exception of the numbers 0 and 1, of any numeric type).

And here comes the important part:

  • 'if' tests on boolean values. That means that whatever expression you give it, it will be converted to either True or False. You can make the same with bool(). And bool((None,)) will return True. The things that will evaluate to False is listed in the docs (linked to by others here)

Now maybe this is only more clear in my head, but at least I tried. :)

like image 80
Lennart Regebro Avatar answered Oct 14 '22 06:10

Lennart Regebro


a is a one-member tuple, which evaluates to True. is test identity of the object, therefore, you get False in all those test. == test equality of the objects, therefore, you get False again.

in if statement a __bool__ (or __nonzero__) used to evaluate the object, for a non-empty tuple it should return True, therefore you get True. hope that answers your question.

edit: the reason True and False are equal to 1 and 0 respectively is because bool type implemented as a subclass of int type.

like image 41
SilentGhost Avatar answered Oct 14 '22 06:10

SilentGhost