True inconsistency in Python

Jimmy Retzlaff jimmy at retzlaff.com
Mon Nov 17 15:01:51 EST 2003


KefX wrote:
...
> I'm not so sure about that. In most languages (including Python),
'false'
> is guaranteed to be only one value (usually zero), therefore comparing
> against it poses no problem. I assume you're saying that doing so
isn't
> problematic in any way, it's just pointless.

In Python the singleton False has exactly one value (as does the
singleton True), but there are many values that are treated as false
when used as an expression being evaluated by "if" including 0, None,
and empty containers ([], {}, "", sets.Set([]), etc.). Comparing a value
directly to False in Python is not a good idea. So, for example, the
following two "if" statements are not equivalent for all possible values
of x:

if not x:
    ...

if x == False:
    ...

The first will execute the body if x == [], the second will not.

...
> But if whatever goes in "blah" is really long (and often it is), you
very
> quickly see what is being compared: it's a straight boolean
comparison,
> whereas with the second you have to look at the whole thing, find no
> comparison operator, and go, "oh, there's no explicit comparison so
it's
> obviously an implicit straight boolean comparison". This is especially
> valuable in really long 'if' statements
...

I agree with Michael Geary that skipping the comparison to True/False
reads much more cleanly. If the expression is too long to be clear, then
you can (should?) encapsulate it in a function or variable that gives
the expression a short descriptive name:

if mouseClickPosition.InRectangle(self.left, self.top,
                                  self.right, self.bottom) == False:
    ...


would probably be more clear like this:


mouseClickInBoundingBox = mouseClickPosition.InRectangle(
                                                self.left, self.top,
                                                self.right, self.bottom)
if mouseClickInBoundingBox:
    ...

...
> Although, as a last thought, it should be relatively easy to make it
so
> that True returns '1' in any comparison except against 0. A class
would be
> able to do this easily by overriding __cmp__:
> 
> def true_class(bool):
>   def __cmp__(self, other):
>     if other:
>       return 1
>     else:
>       return 0
> 
> True = true_class()
...

Similar functionality is already in recent versions of Python:

>>> bool([])
False
>>> bool([1, 2, 3])
True

So, as I believe was pointed out earlier in this thread, if you're
really eager to compare to True and/or False you can do the following
safely:

if bool(x) == True:
    ...

if bool(x) == False:
    ...


Jimmy






More information about the Python-list mailing list