Why comparing a variable to None should be done using is or is not

Asked

Viewed 391 times

3

I’m using PyCharm as an IDE to create my programs in Python, and at a certain point I had to make a comparison between a variable value and None, and I tried to do it with the following code:

if file == None: 
    print("Nothing opened")

but Pycharm is warning me that comparing a variable’s value to None should be done using is or is not. Why?

2 answers

5


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.

2

They are different. The == invokes the method __eq__ of the class to his left. Ja the is really compare equality.

In that case, however.

  • yes. no problem. so it would be weird to do == to the None, since it is strange to compare an object with "nothing" and rather "be" nothing XD

  • when the eq is not equal to equality comparison.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.