Search code examples
pythonpep8

Strange PEP8 recommendation on comparing Boolean values to True or False


At the end of Python PEP 8 I'm reading:

  • Don't compare Boolean values to True or False using ==

     Yes:   if greeting:
     No:    if greeting == True:
     Worse: if greeting is True:
    

I have no problem with that recommendation when the Boolean is True, but it sounds strange when checking for False.

If I want to know if a variable greeting is False, why shouldn't I write the following?

    if greeting == False:

If I write if not greeting: it will have a very different meaning that the above statement. What if greeting is None? What if it is an empty string? Does this PEP 8 recommendation means that variables storing Boolean values should only contains True or False and that None should be avoided for these variables?

To my eyes it looks like a recommendation coming from other languages with static typing and that does not fit well with Python, at least for comparing to False.

And by the way, why is if greeting is True: described as worse than if greeting == True:? Should we also understand that if greeting is False: is also worse that if greeting == False:?


Solution

  • The way I understand it the PEP's recommendation implies that, if you know can be reasonably sure of the type of foo (which is usually the case), then testing for the explicit false value is redundant and reduces readability. For example, in foo = [i for i in range(10) if i == x], you can be fairly sure that the only false value foo can have is [] (assuming no exceptions are raised). In this case it is redundant to use foo == [] and not foo is better.

    On the other hand the semantic value of foo == [] or foo == False is sometimes more valuable and should then be used (IMHO) in stead of not foo. It depends on what, specifically, you are trying to communicate. In fact not foo means "foo has a false value?", whereas foo == False means "foo has the same value as False?".

    The PEP states that everything it contains are guidelines. There are exceptions to rules and this one is no different.