Implicit conversion to boolean in if and while statements
rosuav at gmail.com
Sun Jul 15 23:53:09 CEST 2012
On Mon, Jul 16, 2012 at 4:56 AM, Rick Johnson
<rantingrickjohnson at gmail.com> wrote:
> On Sunday, July 15, 2012 1:01:58 PM UTC-5, Ian wrote:
>> 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?
> Because we are keeping the condition consistent. We are not relying on implicit resolution of an object's value based on some dark, esoteric and inconsistent rules that defy all normal logic.
>> What should "if" do if presented a value that isn't True or False?
>> Raise a TypeError?
> YES! Because IT IS the author's responsibility to present a condition that evaluates to either True or False. Anything else would be ridiculously inconsistent.
Then the construct "if bool(some_condition):" is redundant. What
you've described is a viable system (REXX, for instance, demands that
an IF statement be given strictly either a 1 or a 0 (there's no True
and False values, but you're not allowed to use 527 as a True value,
it has to be 1)), but it's still redundant to attempt the cast. For
instance, this REXX function will logically negate a value twice, thus
forcing it to boolean:
But if it's given a non-bool, it'll just bomb, exactly the same as the
if statement would. So Ian's point still stands.
More information about the Python-list