Implicit conversion to boolean in if and while statements

Ranting Rick rantingrickjohnson at gmail.com
Mon Jul 16 04:58:20 CEST 2012


On Jul 15, 9:15 pm, Devin Jeanpierre <jeanpierr... at gmail.com> wrote:

> For example, instead of "if stack:" or "if bool(stack):", we could use
> "if stack.isempty():". This line tells us explicitly that stack is a
> container. Or instead of "if dist:" or "if bool(dist):" we could use
> "if dist == 0:". This tells us explicitly that stack is a number.
> Supposedly this makes it easier to read code. It certainly reads more
> like English! :)

Yes, but this approach involves adding new "value testing" methods to
every object.

Whilst these specific methods would probably inject more comprehension
than using bool, i believe the bool function can handle this problem
better due to its monolithic and generic nature. No need to memorize
which method is needed for strings, or integers, or lists, etc... just
use bool and everything works. As for the semantics, we should let the
object decide how to respond to a __bool__() request.

But what's the point of having a bool function if we refuse to use it
correctly? We force str, int, and float conversion all day, but not
the bool? Where is the consistency? Where is the bool!?



More information about the Python-list mailing list