<var> is None vs. <var> == None

Steve Holden steve at holdenweb.com
Sat Jan 24 04:02:34 EST 2009


Steven D'Aprano wrote:
> On Fri, 23 Jan 2009 20:33:45 -0500, Steve Holden wrote:
> 
>> Steven D'Aprano wrote:
>>> On Fri, 23 Jan 2009 14:58:34 -0500, Gerald Britton wrote:
>>>
>>>> Hi -- Some time ago I ran across a comment recommending using <var> is
>>>> None instead of <var> == None (also <var> is not None, etc.)
>>> That entirely depends on whether you wish to test for something which
>>> *is* None or something with *equals* None. Those two things have
>>> different meanings.
>>>
>> No they don't, because the language *guarantees* the None object is a
>> singleton, so anything that *equals* None *is* None.
> 
> Twice in one day. Have they put funny chemicals in the water over there? 
> *wink*
> 
Nope, but you know what newsgroup response propagation is like ...

> Steve, in case you missed my earlier response:
> 
>>>> class Empty:
> ...     def __eq__(self, other):
> ...             return not bool(other)
> ...
>>>> e = Empty()
>>>> e == None
> True
>>>> e is None
> False
> 
> 
> An instance that compares equal to anything false doesn't strike me as 
> particularly bizarre or pathological. For instance, the Python Cookbook 
> has an implementation for the Null object pattern. The implementation 
> given compares unequal to everything, but suggests defining an 
> appropriate __eq__ if you need different behaviour.
> 
Sure, my syllogism was not strictly true, hence my final quote:

> Of course there can be pathological objects with bizarre comparison
> methods. And the "is" test helps avoid them.

Personally I believe that the Empty class is at least slightly pathological.

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list