Jeff Widman Jeff Widman - 6 days ago 7
Python Question

Is testing identity different than testing whether in a tuple?

I need to check if a function written by another team returns

True
or
None
.

I want to check for identity, not equality.

I'm unclear what type of check happens when using
in
. Which of the following does
if result in (True, None):
behave like?


  1. if result is True or result is None:

  2. if result or result == None:


Answer

No, they are not the same, because identity testing is a subset of what the in operator does.

if result in (True, None):

Is the same as this:

if result == True or result is True or result == None or result is None:
# notice that this is both #1 and #2 OR'd together

From the docs:

For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y)

The in operator tests for both equality and identity, and either one being true will return True. I got the impression that you're only working with boolean values and None. In that limited case, the in operator will behave the same as both of your other snippets.

However, you said you want identity checking. So I would suggest you use that explicitly so your code's intention and what it is expecting is clear. Furthermore, if there is a bug in the called function and it returns something other than boolean or None, using the in operator can hide that bug.

I would suggest your first alternative:

if result is True or result is None:
    # do stuff
else:
    # do other stuff

Or if you're feeling defensive:

if result is True or result is None:
    # do stuff
elif result is False:
    # do other stuff
else:
    # raise exception or halt and catch fire
Comments