The operator ==
forehead for equality, as long as the is
forehead 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 to compare with None
, often its intention is to know if such a variable is really 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 intent is even compared by equality with None
, there is no problem in using the ==
. But how rarely (ever?) is this useful in practice, when you see a code using it == None
or != None
it is usually assumed that it was a mistake by the programmer, and not something he purposefully did.
Relacionados: http://answall.com/questions/18910/qual-a-diferen%C3%A7a-no-uso-do-m%C3%A9todo-equals-para-o-operador
– ptkato
See also: In Python, what are the consequences of using is instead of '=='
– Bacco