The ==
operator tests for equality , while is
tests for identity . In other words, x is y
will only return True
if x
and y
are the same object (and not merely "equal"):
>>> x = [1, 2, 3] # x é um objeto
>>> y = [1, 2, 3] # y é outro
>>> print(x == y) # eles são iguais (mesmo tipo, mesmo tamanho, mesmos elementos)
True
>>> print(x is y) # mas não são "o mesmo objeto" - se mexer em um, o outro não é afetado
False
>>> z = x # z é outra referência para o mesmo objeto x
>>> print(x is z) # então eles são efetivamente "o mesmo objeto"
True
As for comparing with None
, it is often intended to know if such a variable is actually empty - and not only contains a value that is "equal to empty":
>>> class Vazio(object):
... def __eq__(self, obj):
... return obj is None
...
>>> v = Vazio()
>>> print(v == None)
True
>>> print(v is None)
False
>>> v == v # Pela regra "louca" do Vazio.__eq__, v é diferente de si próprio!
False
>>> v is v # Mas obviamente, ainda é o mesmo objeto
True
If your intention even compares by equality with None
, there is no problem in using ==
. But as seldom (never?) This is useful in practice, when you see a code using == None
or != None
it is usually assumed that it was a programmer's mistake, not something that he purposely did.