Identity Is Not The Same As Equality

19 Jan 2016

Identity operator (is) and equality operator (==) really are two different things.

Identity operator tests if two objects are the same: id(obj1) == id(obj2) is equivalent to obj1 is obj2.

Equality operator tests if the values of two objects are the same. Most of the time in a program, this is what you want: if a == 2 or if s == 'dumb'. But (there is always a but) you also see code like this: if a is None, which is also a recommended pythonic style in PEP08. What is going on here?

This is one of the nuances of Python. None is a singleton object, that means there is only one None object ever, and therefore tests like if a is None would make sense. And according to PEP08:

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

So yes, use identity operator for testing None, but use equality operator for testing other non-singleton object values, including strings. Hmmm, this is probably one of the things I do not like in Python, it seems arbitrary and inconsistent.