Implicit conversion to boolean in if and while statements

Rick Johnson rantingrickjohnson at gmail.com
Fri Feb 8 06:53:08 CET 2013


On Monday, July 16, 2012 8:45:51 PM UTC-5, rusi wrote:
> On Jul 15, 9:50 pm, Rick Johnson <rantingrickjohn... at gmail.com> wrote:

> > I think this issue is not so much a "bool test" vs "type
> > test", but more an ambiguous syntax issue.
> > 
> 
> If you know some English, its clear that if and while
> create bool contexts. 

Wrong. "if and "while" do not /create/ anything. On a syntactical level they merely /suggest/ to the reader that the following statement is expected to be a boolean value. It is the /statement/ itself that creates the boolean value, not the keywords! 

Observe:

    0 == 0 -> True
    isinstance("5", int) -> False
  
You see, "if" and "while" don't create anything, in reality they merely execute a block of code depending on the value of the statement that follows the keyword. "if" and "while" are only *logical switches* and nothing more. You could write a simple quasi-example of "if" as a function like this:

    def if_(value):
        if not value:
            return
        # do_something_here

  
Those previous statements where /explicit/, and as such need no bool() function to resolve their Boolean values, however, consider the following /implicit/ conversions to Boolean:

    [] -> False
    [1] -> True
    "" -> False
    "1" -> True
    0 -> False
    1 -> True
    2 -> True
    etc...
  
It is my strong opinion that these types of implicit conversions are evil obfuscations of the truth. If we want to convert an object to a Boolean, then use the bool() function on that object:

    bool([]) -> False
    bool([1]) -> True
    etc...
  
Heck! Why even have a damn bool function if you're never going to use it?
  
> [If you know English but have not
> studied logic the 'if/while' make sense whereas 'bool' is
> gobbledygook]

And which Univeristy would you recommend for studying the intricacies of "gobbledygook"? ;-)




More information about the Python-list mailing list