Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

python - 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:?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...