Why the comparison of a variable with None must be done using is or is not

3

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

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

but PyCharm is warning me that comparing a value of a variable with None should be done using is or is not . Why?

    
asked by anonymous 23.09.2014 / 23:25

2 answers

6

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.     

23.11.2014 / 03:10
3

They are different. The == invokes the method __eq__ of the class to the left of it. The is compares equality even.

In that case, however, it does not.

    
23.09.2014 / 23:35