Implicit conversion to boolean in if and while statements

Rick Johnson rantingrickjohnson at gmail.com
Sun Jul 15 12:50:05 EDT 2012


On Sunday, July 15, 2012 11:19:16 AM UTC-5, Ian wrote:
> On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
> > (For the record, I can only think of one trap for the unwary: time
> > objects are false at *exactly* midnight.)
> 
> Ugh, that's irritating.  I can't think of any scenario where I would
> ever want the semantics "if timeval (is not midnight):".  This
> reinforces the point that if you only want to test whether you have
> None, you should use "is not None" rather than relying on __bool__.

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. 

We must NEVER present "if" in such confusing manner as ExampleA. I believe Guido made a grave mistake allowing this syntax to flourish. His intentions where noble, to save people a few keystrokes, but all he accomplished was to pave a road directly into hell. 

 "Explict is better than Implict"



More information about the Python-list mailing list