Is It Better to Use "==" or "is" Operator for None Comparison in Python?

It is possible to do comparisons against None using equality (== or !=):

if foo == None:
    # do something

if bar !== None:
    # do something

However, it is not recommended; you should instead use the is (or not is) operators for identity checks:

if foo is None:
    # do something

if bar is not None:
    # do something

This is also supported by PEP, which states:

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

The reason for this is because:

  • is (or is not) actually checks for an object's identity (i.e. whether two objects are indeed the same object);
  • Equality (== or !=) is applied by calling the __eq__() (or __ne__()) method of an object, which can be overridden. This means that how two objects are considered "equal" can differ from object to object.

For example:

class Foo():
    def __eq__(self, obj):
        return obj is None

foo = Foo()

print(foo == None) # True
print(foo is None) # False

In the example above, you can see that foo and None are actually not the same objects, and thus, correctly fail the identity check with the is operator. Comparatively, this is different when checking for equivalence (as shown in the example above), which can have a different meaning depending on the definition (if any) in the object class.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.