Strange PEP8 recommendation on comparing Boolean values to True or False

kriss picture kriss · Oct 29, 2010 · Viewed 8.9k times · Source

At the end of python PEP8 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 recommandation when the boolean is True, but it sounds strange when checking for False

If I want to know if variable greeting is False why shouldn't I write:

    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 empty string ? Does this PEP8 recommandation 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 recommandation 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, does anyone know why if greeting is True: is described as worse that if greeting == True: ? Should we also understand that if greeting is False: is also worse that if greeting == False: ?

Answer

paxdiablo picture paxdiablo · Oct 29, 2010

I believe you're reading it wrong. Try not to think of greeting as a noun so much as a verb ("I am greeting" instead of "This is a greeting").

You can see the clue in the preamble to PEP8:

One of Guido's key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code.

To that end, code should resemble the written or spoken word as much as possible. You don't say "If I am annoying you is true, let me know" in real life, you just say "If I am annoying you, let me know".

That's one reason why you tend to see boolean variables like isOpen and hasBeenProcessed a lot since they aid in readability of the code.

You should never do something like:

if (isOpen == True)

or:

if (customerDead == False)

simply because you already have a boolean value in the variable name. All the equality is giving you is another boolean value and, invoking reduction ad absurdum, where would you stop?

if (isComplete == True) ...
if ((isComplete == True) == True) ...
if (((isComplete == True) == True) == True) ...
if ((((isComplete == True) == True) == True) == True)...