Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

People also ask

Should I use is none or == None?

In this case, they are the same. None is a singleton object (there only ever exists one None ). is checks to see if the object is the same object, while == just checks if they are equivalent. But since there is only one None , they will always be the same, and is will return True.

Should I use is none or == None Python?

Introduction to the Python None valueIt's a good practice to use the is or is not operator to compare a value with None . Note that you cannot override the is operator behavior like you do with the equality operator ( == ).


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

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).


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.


(ob1 is ob2) equal to (id(ob1) == id(ob2))


The reason foo is None is the preferred way is that you might be handling an object that defines its own __eq__, and that defines the object to be equal to None. So, always use foo is None if you need to see if it is infact None.


There is no difference because objects which are identical will of course be equal. However, PEP 8 clearly states you should use is:

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