Implicit conversion to boolean in if and while statements
Ranting Rick
rantingrickjohnson at gmail.com
Sun Jul 15 22:31:23 EDT 2012
On Jul 15, 8:51 pm, Chris Angelico <ros... at gmail.com> wrote:
> On Mon, Jul 16, 2012 at 11:21 AM, Ranting Rick
>
> <rantingrickjohn... at gmail.com> wrote:
> > If HOWEVER we want to "truth test" an object (as in: "if obj") we
> > should be FORCED to use the bool! Why? Because explicit is better than
> > implicit and readability counts if we want to create maintainable code
> > bases!
>
> > 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.
>
> ChrisA
My point is no different than this example:
py> cost = 1.75
py> cost
1.75
py> 'Cost = ' + cost
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
'Cost = ' + cost
TypeError: cannot concatenate 'str' and 'float' objects
py> 'Cost = ' + str(cost)
'Cost = 1.75'
We DON'T want Python to silently convert "cost" to a string. What we
DO want is to force the author to use the str function thereby making
the conversion explicit.
Same with converting objects to bools.
We DON'T want "if" to magically convert a non-boolean into a boolean.
What we DO want is to force the author to use the bool function
thereby making the conversion explicit. By doing so we transform
confusion into comprehension. By doing so we maintain the principals
of readability counts.
More information about the Python-list
mailing list