Implicit conversion to boolean in if and while statements

MRAB python at mrabarnett.plus.com
Fri Feb 8 18:14:23 CET 2013


On 2013-02-08 07:22, Steven D'Aprano wrote:
> 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).
>
Anything that's not falsey is truey.

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



More information about the Python-list mailing list