Implicit conversion to boolean in if and while statements
jeanpierreda at gmail.com
Mon Jul 16 04:15:13 CEST 2012
On Sun, Jul 15, 2012 at 9:51 PM, Chris Angelico <rosuav at gmail.com> wrote:
>> if bool(obj) and a==b: # Correct!
>> if obj and a==b: # Incorrect!
> That still doesn't answer the question of what bool(obj) should do if
> obj is not a bool, and why if can't do the exact same thing, since if,
> by definition, is looking for a boolean state selector.
If can obviously do the exact same thing -- it does, in Python.
I don't agree with the angle that Rick is spinning, so let me write my
own: By forcing the objects in conditional to be booleans, you are
forced to do something to non-booleans to convert them. By doing so,
you will help inform the reader what the non-boolean is, which makes
it easier for them to figure out the code.
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! :)
As far as I know, the only use of having a polymorphic boolean
conversion is reducing the amount of typing we do. Generally objects
with otherwise different interfaces are not interchangeable just
because they can be converted to booleans, so you wouldn't lose much
by being forced to explicitly convert to boolean with something
More information about the Python-list