<var> is None vs. <var> == None
steve at holdenweb.com
Fri Jan 23 21:28:38 CET 2009
Chris Rebert wrote:
> On Fri, Jan 23, 2009 at 11:58 AM, Gerald Britton
> <gerald.britton at gmail.com> 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.) 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.
>> I'm looking for a (semi)-official statement on this, but couldn't find
>> one with normal googling. Can someone please send a link?
>>From http://www.python.org/dev/peps/pep-0008/ ,
> 2nd bullet under "Programming Recommendations":
> - Comparisons to singletons like None should always be done with
> 'is' or 'is not', never the equality operators.
> Just FYI, `is` compares object identity (pointer equality) whereas ==
> checks for value equivalence (which causes a method call). This is why
> it's significantly faster.
> But the main reason is because it's idiomatic.
And, just for completeness, the "is" test is canonical precisely because
the interpreter guarantees there is only ever one object of type None,
so an identity test is always appropriate. Even the copy module doesn't
create copies ...
>>> import copy
>>> n = copy.copy(None)
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list