is None or == None ?
mrkafk at gmail.com
Fri Nov 6 15:32:52 CET 2009
Stefan Behnel wrote:
> mk, 06.11.2009 14:20:
>> Some claim that one should test for None using:
>> if x is None:
> Which is the correct and safe way of doing it.
>> ..but the standard equality which is theoretically safer works as well:
>> if x == None:
> Absolutely not safe, think of
> class Test(object):
> def __eq__(self, other):
> return other == None
> print Test() == None, Test() is None
Err, I don't want to sound daft, but what is wrong in this example? It
should work as expected:
>>> class Test(object):
... def __eq__(self, other):
... return other == None
>>> Test() is None
>>> Test() == None
My interpretation of 1st call is that it is correct: instance Test() is
not None (in terms of identity), but it happens to have value equal to
None (2nd call).
Or perhaps your example was supposed to show that I should test for
identity with None, not for value with None?
That, however, opens a can of worms, sort of: whether one should compare
Test() for identity with None or for value with None depends on what
programmer meant at the moment.
More information about the Python-list