"x == None" vs "x is None"

Chris Angelico rosuav at gmail.com
Sun Jan 17 05:15:21 EST 2016


On Sun, Jan 17, 2016 at 8:51 PM, Ulli Horlacher
<framstag at rus.uni-stuttgart.de> wrote:
> I have seen at several places "x == None" and "x is None" within
> if-statements.
> What is the difference?
> Which term should I prefer and why?

tl;dr: Prefer "x is None" as a check.

The two checks have slightly different meaning, and almost always you
want the identity check. "x is None" is asking the identity question
"does the name x refer to the exact same object as the singleton
None", but "x == None" is asking the value question "does the object
referred to by x want to consider itself equal to None". For instance:

class NoneLike(object):
    def __eq__(self, other):
        if other is None: return True
        return isinstance(other, NoneLike)

>>> x = NoneLike()
>>> x == None
True
>>> x is None
False

The object referred to as x is not None itself, but it has decided to
call itself equal to None. This is incredibly unusual, and will
generally not be what you want.

As an additional bonus, the identity check is faster. The equality
check has to ask the object if it's equal or not, but the identity
check just says "same object? Y/N", which is generally going to be a
cheap check (in CPython, the objects' pointers can be compared).

But the main reason is semantic - you generally do not _want_ the
possibility of objects comparing equal to None. And if you actually
do, you'd better have some kind of comment there, or someone will come
along and change your code to the more normal "is None".

ChrisA



More information about the Python-list mailing list