Boolean comparison & PEP8

Michael F. Stemper michael.stemper at gmail.com
Mon Jul 29 13:44:40 EDT 2019


On 28/07/2019 19.04, Chris Angelico wrote:
> On Mon, Jul 29, 2019 at 9:48 AM Michael Torrie <torriem at gmail.com> 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.
> 
> This is a fairly unusual case, though. More commonly, the default
> would be None, not False, and "if bar is None:" is extremely well
> known and idiomatic.

That's certainly how I would have done it until I read your post. But
reading it immediately raised the question of why not:

 def foo( bar=[] ):
   if len(bar)==0:
     print( "Pretty short" )
   else:
     print( bar )
   return

Seems to work just fine.


-- 
Michael F. Stemper
Deuteronomy 24:17



More information about the Python-list mailing list