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

前端 未结 7 2119
谎友^
谎友^ 2020-12-08 06:26

I did several Boolean Comparisons:

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

It sounds like

相关标签:
7条回答
  • 2020-12-08 07:03

    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.
    0 讨论(0)
提交回复
热议问题