[Python-ideas] Programming recommendations (PEP 8) and boolean values

Terry Reedy tjreedy at udel.edu
Wed Aug 8 18:51:13 CEST 2012

On 8/8/2012 10:11 AM, Michael Foord wrote:
> Hey all,
> True and False are singletons, so if you want to check precisely for
> True and False then an identity check seems appropriate.
> However the "Programming Recommendations" section of PEP 8 has this to
> say on the topic:
> Don't compare boolean values to True or False using ==.
> Yes:   if greeting:
> No:    if greeting == True:
> Worse: if greeting is True:
> http://www.python.org/dev/peps/pep-0008/#programming-recommendations

I understand 'boolean values' to when you KNOW that <greeting> is a 
boolean. For instance 'isinstance(x, tuple)'. In that situation, 'if 
isinstance(x, tuple) is True' is a stupid redundancy, since the actual 
test, with the internal comparison, becomes 'if (isinstance(x, tuple) is 
True) is True'. An newbies not really understanding 'if' have done the 
latter, as seen on python-list

On the other hand, when the tested value might not be boolean

for item in [1, None, 'a', True, []]:
     if item is True:

'is True' is necessary.

> It seems to me that there is an important distinction between testing
> that an object is either the boolean True or False and merely checking
> the "truthiness" of an object.

That is the distinction drawn above.

> Many a bug has been caused by an empty
> container object (or some other falsey object) falling into an "if not
> value" clause that was actually meant to check for the presence of False
> or None.

One should generally know what group of classes one is testing in any if.

Terry Jan Reedy

More information about the Python-ideas mailing list