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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Jan 23 18:49:11 EST 2009


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.

I wonder, do newbies actually get the impression from somewhere that "is" 
is a synonym for "=="?



> 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.



-- 
Steven



More information about the Python-list mailing list