Boolean comparison & PEP8

Jonathan Moules jonathan-lists at lightpear.com
Sun Jul 28 07:55:34 EDT 2019


Hi List,
Lets say I want to know if the value of `x` is bool(True).
My preferred way to do it is:

if x is True:
     pass

Because this tests both the value and the type.

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:
"""

Why?

If `x` can also have a value of "1"(str) or 1(int) then in both cases 
this would be a false positive if I were to do the below as they'll both 
equate to True:

if x:
     pass

The PEP for boolean type (285 - 
https://www.python.org/dev/peps/pep-0285/) doesn't mention the "is" 
comparison keyword at all as far as I can tell.

What am I missing?
Thanks






More information about the Python-list mailing list