The Python Oracle

What is the difference between "is None" and "== None"

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping

--

Chapters
00:00 What Is The Difference Between &Quot;Is None&Quot; And &Quot;== None&Quot;
00:17 Answer 1 Score 70
00:46 Accepted Answer Score 508
01:15 Answer 3 Score 238
01:22 Answer 4 Score 8
01:32 Thank you

--

Full question
https://stackoverflow.com/questions/3257...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 508


The answer is explained here.

To quote:

A class is free to implement comparison any way it chooses, and it can choose to make comparison against None mean something (which actually makes sense; if someone told you to implement the None object from scratch, how else would you get it to compare True against itself?).

Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None as a general rule.




ANSWER 2

Score 238


class Foo:
    def __eq__(self, other):
        return True
foo = Foo()

print(foo == None)
# True

print(foo is None)
# False



ANSWER 3

Score 70


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.

For example:

p = [1]
q = [1]
p is q  # False because they are not the same actual object
p == q  # True because they are equivalent

But since there is only one None, they will always be the same, and is will return True.

p = None
q = None
p is q  # True because they are both pointing to the same "None"



ANSWER 4

Score 8


If you use numpy,

if np.zeros(3) == None: pass

will give you an error when numpy does elementwise comparison.