Implicit conversion to boolean in if and while statements

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Jul 15 06:56:57 EDT 2012


On Sun, 15 Jul 2012 03:34:46 -0500, Andrew Berg wrote:

> This has probably been discussed before, 

By the hoary hosts of Hoggoth, has it ever!

> but why is there an implicit
> conversion to a boolean in if and while statements?

It's nothing to do with if and while. All Python objects are duck-typed 
as bools.

1) It's generally part of the duck-typing philosophy. If an object quacks 
like a bool, why not treat it as a bool?

2) It's useful and convenient for short-circuit boolean expressions such 
as any(), all(), and various things like:

    for x in mylist or []: 
        ...

is better than:

    if mylist is not None:
        for x in mylist: 
            ...

3) Rather than distinguishing "true" from "false", a more useful 
dichotomy is between "something" and "nothing". Python includes a number 
of ways of spelling "nothing" of various types, such as:

    None, 0, 0.0, '', [], {}, set()

and nearly everything else is "something".

4) Other languages such as Ruby, Javascript, PHP, Clojure and others also 
distinguish between true-like and false-like ("truthy" and "falsey") 
values. Although some of them have made some pretty weird and arbitrary 
choices for what counts as true-like and false-like, without Python's 
general principle that "nothing" values should be false.

(E.g. Javascript considers Boolean(false) to be a true value!!!)

5) Prior to Python 2.2, there was no bool type and no True and False 
values. In fact, here is an impassioned plea from an educator begging 
Guido not to introduce True and False to the language, because duck-typed 
truthy/falsey values are *so much better*.

http://groups.google.com/group/comp.lang.python/msg/2de5e1c8384c0360?hl=en

Sadly, or happily, Python did grow True and False values, but the 
fundamental distinction between something and nothing still exists.

(For the record, I can only think of one trap for the unwary: time 
objects are false at *exactly* midnight.)


-- 
Steven



More information about the Python-list mailing list