Implicit conversion to boolean in if and while statements

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Feb 8 02:22:27 EST 2013


Rick Johnson wrote:

> Why even have a damn bool function if you're never going to use it?

bool is for converting arbitrary objects into a canonical True or False
flag. E.g. one use-case is if you wish to record in permanent storage a
flag, and don't want arbitrary (possibly expensive) objects to be recorded.

Most of the time, you shouldn't care whether you have a canonical True/False
bool, you should only care whether you have something which duck-types as a
boolean flag: a truthy or falsey value. In Python, all objects duck-type as
flags. The usual interpretation is whether the object represents something
or nothing:

"nothing", or falsey values: None, False, 0, 0.0, '', [], {}, set(), etc.
(essentially, the empty value for whichever type you are considering)

"something", or truthy values: True, 1, 2.5, 'hello world', etc.
(essentially, non-empty values).

Prior to Python 3, the special method __bool__ was spelled __nonempty__,
which demonstrates Python's philosophy towards duck-typing bools.


-- 
Steven




More information about the Python-list mailing list