Implicit conversion to boolean in if and while statements

Ian Kelly ian.g.kelly at gmail.com
Sun Jul 15 20:01:58 CEST 2012


On Sun, Jul 15, 2012 at 10:50 AM, Rick Johnson
<rantingrickjohnson at gmail.com> wrote:
> I think this issue is not so much a "bool test" vs "type test", but more an ambiguous syntax issue. Consider this:
>
> ## EXAMPLE A ##
> py> if money:
> ...     do_something()
>
> The syntax "if money" implies we are testing/measuring some attribute of "money", but what exactly about money are we testing/measuring? The problem lies in the syntax. To understand this syntax, we must first interpret what *IF* means, and we should *NEVER* need to interpret such a well defined word as *IF*! This syntax is far too opaque. Consider the alternative:
>
> ## EXAMPLE B ##
> py> if bool(money):
> ...     do_something()
>
> Now we have a hint. Even if we don't understand the inner workings of the "bool" function, we *do* understand that the statement "bool(money)" *must* return True or the block *will not* execute.

So now instead of having to understand how "if" handles arbitrary
values, we have to understand how "bool" handles arbitrary values.
How is that an improvement?

What should "if" do if presented a value that isn't True or False?
Raise a TypeError?

Next thing we know, people get so used to wrapping everything they
present to "if" in a "bool()" call, that they start writing silly
things like "if bool(x == 7)" and "if bool(isinstance(x, int))".  Why?
 Because it's faster and easier to automatically wrap the value in
"bool" than it is to put in the effort to verify that the value will
always be a bool to begin with in order to avoid a useless and
annoying exception.  At the point that happens, the "bool()" is
effectively just part of the if syntax, and we're back to where we
started.



More information about the Python-list mailing list