The style guide reads:
# Correct:
if greeting:
# Wrong:
if greeting == True:
# Worse:
if greeting is True:
See PEP 8, search for the word "worse"
Why is this? I am accustomed to checking conditions as explicit as possible, to make the code more readable, and to catch aberrations.
Consider this function:
def f(do_it):
if do_it : print("doit")
else : print("no don't")
It is easy to abuse/oversee, with unexpected behaviour
>>> f("False")
doit
>>> f([False])
doit
This is a real problem when, for instance, you are checking a return value that could unintentionally pass an if clause. This could be avoided by using the is
construct.
Clearly there's a good reason for the PEP recommendation, but what is it?
Further research, prompted by the commenters, lead me to the following findings:
if x:
invokes the __bool method of the class of x. The method should return True or False depending on which of the two the object deems itself to be.
if x==True:
invokes the __eq method of the class of x. The method should be able to compare itself to True (or False), and return True or False, as the case may be.
if x is True
invokes neither. This tests whether x is the "True" object. It completely circumvents the __eq and __bool methods.
Note: I am not asking about the difference between ==
and is
. If that's why you are here, see Is there a difference between "==" and "is"?