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

Steve Holden steve at holdenweb.com
Fri Jan 23 20:33:45 EST 2009


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.

> I wonder, do newbies actually get the impression from somewhere that "is" 
> is a synonym for "=="?
> 
Who knows. But if they do they can easily be reeducated.
> 
> 
>> My own
>> testing indicates that the former beats the latter by about 30% on
>> average.  Not a log for a single instruction but it can add up in large
>> projects.
> 
> If you have a "large" project where the time taken to do comparisons to 
> None is a significant portion of the total time, I'd be very surprised.
> 
> var is None is a micro-optimization, but that's not why we do it. We do 
> it because usually the correct test is whether var *is* None and not 
> merely equal to None. Any random object might happen to equal None 
> (admittedly most objects don't), but only None is None.
> 
Of course there can be pathological objects with bizarre comparison
methods. And the "is" test helps avoid them.

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