Boolean comparison & PEP8

Richard Damon Richard at Damon-Family.org
Sun Jul 28 20:14:27 EDT 2019


On 7/28/19 7:46 PM, Michael Torrie wrote:
> On 7/28/19 5:55 AM, Jonathan Moules wrote:
>> But this appears to be explicitly called out as being "Worse" in PEP8:
>>
>> """
>> Don't compare boolean values to True or False using ==.
>>
>> Yes:   if greeting:
>> No:    if greeting == True:
>> Worse: if greeting is True:
>> """
> Yet the recommended solution to the problem of wanting a default
> argument of an empty list is something like this:
>
> def foo(bar=False);
>     if bar is False:
>         bar = []
>
>     ....
>
> Clearly in this case the expression "not bar" would be incorrect.
>
> There's a difference between looking for a particular identity or
> sentinel, and checking for truthiness or falsiness.
>
> So I guess it all depends on what you need to do. If you just need to
> check truthiness, just do "if greeting"  If you need to know if the
> variable is some particular sentinel, use the "if greeting is whatever".

I thought the recommended value was None, not False (so you don't need
to ask why not True). I suppose if None is a valid value for the input
you would need something else, and False is one possibility.

-- 
Richard Damon




More information about the Python-list mailing list