Identity vs. Equality: When to use "is/is not" versus equality operators "==/!=" in Python

Identity vs. Equality: When to use is/is not versus equality operators ==/!= in Python

Hello to my fellow JavaScript developers.

I don't really think of myself as an active JS developer but the very strong background is there.

So we are used to checking for strict equality like this === and inequality like this !==. There is such a thing as loose equality == but that is beyond the scope of this blog post. Therefore, in Python you might think that we would always use the Python equivalent equality operators at all times: == and =!.

However, this is not the case for two data types, which is:
  • None
  • Booleans
In this case, it is better to use is and is not respectively.

This is the case for example when we are testing. 

You could have something in a test where for example

assert member.vip is False

If you were checking if a member is not a VIP in your Django model database.

A bit more info on this please 

So the slight difference here is that:
  • == checks for equality
  • is checks for identity equality 
    • so this means that it checks for whether the two objects are the same instance in memory
    • The reason why None and Booleans are better checked for with is in Python is because of the fact that they are both something that is called a "singleton".

Equality vs. Identity

Basically, equality checks if two values are the same; 

If 

number_1 = 5

number_2 =5

number_1 == number_2

this is true because they have the same value, although they do not point to the same object in memory.

Wheres is only checks for whether the two objects are the same instance in memory.
  • A singleton is a design pattern where only one instance of a class exists in memory.
  • None, True and False are singletons, so therefore using is for comparison is both clearer in intention and more efficient.
identity vs equality: checking when to use "is/is not" over "==/!=" in Python. Pictures of code in the background. Colourful text.



Comments