This simplicity of the identity comparison provides its main advantage over equality. When you test equality of an object, arbitrary code could be running, and an arbitrary result could be returned. Identity will do a simple comparison and return a Boolean.

That said, equality will generally be the preferred operation. In most cases, you will care about the value of an object, not its identity. If you want to test if a user entered a particular string, you care about the value of that string, not the details of how the Python interpreter is storing it.

There are two primary cases where identity checking is preferred:

  1. To understand if the same object shows up with different names in different places. This is relatively rare, but sometimes you do need to know this.
  2. To compare a value to a flag value. In Python, this is most likely to be the value None (although others exist and modules can create their own). These are used to indicate some condition. The actual value is unimportant; all information is simply in the value being used. Therefore, it’s generally preferred to test value is None over value == None. Odd data types could define that equality to be true, but the identity check will be false. (This is made possible by the fact that None is a singleton—there is a single None object in the Python interpreter.)


Hopefully, this all seems relatively straightforward. If so, please read the follow-up article where we discuss a number of confusing subtleties about how this all works. Stay tuned for part II!

Source link

Leave a Reply

Your email address will not be published.