Is there any difference between "foo is None" and "foo == None"?

Solution 1:

is always returns True if it compares the same object instance

Whereas == is ultimately determined by the __eq__() method

i.e.


>>> class Foo(object):
       def __eq__(self, other):
           return True

>>> f = Foo()
>>> f == None
True
>>> f is None
False

Solution 2:

You may want to read this object identity and equivalence.

The statement 'is' is used for object identity, it checks if objects refer to the same instance (same address in memory).

And the '==' statement refers to equality (same value).

Solution 3:

A word of caution:

if foo:
  # do something

Is not exactly the same as:

if x is not None:
  # do something

The former is a boolean value test and can evaluate to false in different contexts. There are a number of things that represent false in a boolean value tests for example empty containers, boolean values. None also evaluates to false in this situation but other things do too.