Implicit conversion to boolean in if and while statements

Terry Reedy tjreedy at udel.edu
Sun Jul 15 22:28:02 CEST 2012


On 7/15/2012 1:02 PM, Andrew Berg wrote:
> On 7/15/2012 5:56 AM, Steven D'Aprano wrote:
>> 3) Rather than distinguishing "true" from "false", a more useful
>> dichotomy is between "something" and "nothing". Python includes a number
>> of ways of spelling "nothing" of various types, such as:
>>
>>      None, 0, 0.0, '', [], {}, set()
>>
>> and nearly everything else is "something".
> Okay, I see the value in this, but I don't understand why None has a
> truth value.

Because everything does (or should).

 > I would expect None to mean "doesn't exist" or "unknown" or
> something like that - e.g., a value of 0 means 0 jelly beans in the jar
> and None means there isn't a jar.
>
> FWIW, I have, for a reason I forget, gotten into the habit of writing
> "if x is not None" when testing for None.

If x might possibly be any other false value (as is, I think, the usual 
case), that is the right thing to do. Even if no other false value is 
possible, I would still use 'is not None' just to be clear what the 
false alternative is, and to guard against mistakes (like not knowing 
that time values can be false) or code changes that add the possibility 
of ohter false values.

> However, I have not been
> writing "if x is True: ..."/"elif x is False: ..."/"else: 'ruh-roh'"
> when testing for True (in cases where a value of True or False makes
> sense, but any other value would not). Should I?

If you only want to execute the if branch when x is literally the bool 
object True and x could be some other non-bool true value such as 1 or 
'a' or [1], etc, then you should.

If x is guaranteed to be True or False, which is the case you more or 
less proposed, then you should not. For instance, "if isinstance(x, int) 
is True:" or "if (n > 3) is True:" are redundant.

-- 
Terry Jan Reedy






More information about the Python-list mailing list