is None or == None ?

Daniel Fetchinson fetchinson at googlemail.com
Fri Nov 6 09:51:56 EST 2009


> Some claim that one should test for None using:
>
> if x is None:
>
> ..but the standard equality which is theoretically safer works as well:
>
> if x == None:
>
> So, which one is recommended?

It depends on what you want to do. There is no single answer to your
question, until you tell us what your context is.

The None object in python is a singleton. If you want to check whether
a given object is this singleton None object (note that this is
unambiguous, it either occupies the same address in memory as the
singleton None or it doesn't) then you should use 'x is None'.

If, however you want to test for equality, you should use 'x == None'.
An object 'x' may implement equality checks in a funny way and it may
be that 'x == None' is True although 'x is None' is False. But it may
be that this is exactly what you want, because the author of the
object 'x' intentionally has written the equality check code to make
this so. In this case you need 'x == None'.

So unless you tell us in what context you are asking this question,
there is no single answer to it.

Cheers,
Daniel



-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown



More information about the Python-list mailing list