is None or == None ?

Stefan Behnel stefan_ml at behnel.de
Sat Nov 7 02:20:20 EST 2009


mk, 06.11.2009 15:32:
> Stefan Behnel wrote:
>>    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
> False
> >>> Test() == None
> True

Yes, and it shows you that things can compare equal to None without being None.


> Or perhaps your example was supposed to show that I should test for
> identity with None, not for value with None?

Instead of "value" you mean "equality" here, I suppose. While there are
certain rare use cases where evaluating non-None objects as equal to None
makes sense, in normal use, you almost always want to know if a value is
exactly None, not just something that happens to return True when
calculating its equality to None, be it because of a programmer's concious
consideration or buggy implementation.

Stefan



More information about the Python-list mailing list