True inconsistency in Python

Scott Chapman scott_list at mischko.com
Wed Nov 12 22:42:27 EST 2003


There seems to be an inconsistency here:

Python 2.3.2 (#1, Oct  3 2003, 19:04:58)
[GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2
>>> 1 == True
True
>>> 3 == True
False
>>> if 1: print "true"
...
true
>>> if 3: print "true"
...
true

>>> 0 == False
True
>>> -1 == False
False
>>> -1 == True
False
>>> if -1:  print "true"
...
true
>>> if -2: print "true"
...
true

>>> if None:
...   print "hello"
...
>>> x = None
>>> x == None
True
>>> x == True
False
>>> x == False
False
>>> x <> True
True
>>> x <> False
True
>>> None == True
False
>>> None == False
False


Historically Python has allowed <> 0 to equal true in evaluations.  Now 
<> 0 still evaluates to true in evaluations. However it doesn't equal  
True.  They are not interchangable.  (Same with empty lists, etc.) 
Assuming the old behavior is desired, programmers need to be careful 
not to compare a variable with True as in:

if var == True: # only works if var is 1
  blah

' Must use:

if var: # works if var is not 0
  blah

Is this inconsistency going to be resolved in the future?

How?  (Will <>0 == True or will <>0 <> true or will it be resolved some 
other way that I'm too opaque to see? :-)

It seems that maybe Python should throw a warning (perhaps if a flag is 
set) any time it bumps into code comparing a variable to True or False. 
It's pretty subtle and would easily throw a newbie.

Of course, according to the above logic, if 1 == true and 2 == true, 
then 1 == 2! Thankfully this doesn't work in Python.  Python is magic.  
I love the magic but it creates some interesting inconsistencies.

Scott






More information about the Python-list mailing list