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
179 views
in Technique[技术] by (71.8m points)

python - Is it safe to replace '==' with 'is' to compare Boolean-values

I did several Boolean Comparisons:

>>> (True or False) is True
True
>>> (True or False) == True
True

It sounds like == and is are interchangeable for Boolean-values.

Sometimes it's more clear to use is

I want to know that:

Are True and False pre-allocated in python?

Is bool(var) always return the same True(or False) with the pre-allocated True(or False)?

Is it safe to replace == with is to compare Boolean-values?


It's not about Best-Practice.

I just want to know the Truth.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You probably shouldn't ever need to compare booleans. If you are doing something like:

if some_bool == True:
  ...

...just change it to:

if some_bool:
  ...

No is or == needed.

As commenters have pointed out, there are valid reasons to compare booleans. If both booleans are unknown and you want to know if one is equal to the other, you should use == or != rather than is or is not (the reason is explained below). Note that this is logically equivalent to xnor and xor respectively, which don't exist as logical operators in Python.

Internally, there should only ever be two boolean literal objects (see also the C API), and bool(x) is True should be True if bool(x) == True for any Python program. Two caveats:

  • This does not mean that x is True if x == True, however (eg. x = 1).
  • This is true for the usual implementation of Python (CPython) but might not be true in other implementations. Hence == is a more reliable comparison.

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

...