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

Python "x == None" vs. "x is None"

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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.