Steven D'Aprano steve at
Tue Mar 4 05:52:38 CET 2014

On Tue, 04 Mar 2014 00:22:55 +0200, Marko Rauhamaa wrote:

> Jerry Hill <malaclypse2 at>:
>> except for the fact that there has been 20 years of custom saying that
>> comparing to None with equality is wrong.
> "if foo == None" is not wrong in any manner. It's just that if you are
> comfortable with the "is" operator and its semantics, "if foo is None"
> is slightly more natural.
> You generally use "==" if more than one object could be equal. If you
> know there's only one object of the kind, you convey that knowledge by
> the use of "is" even when functionally, it doesn't matter.

I don't agree that it doesn't matter. Code, even when functionally 
equivalent, should express the intention of the programmer in as simple a 
fashion as is possible given the constraints of the task, performance, 
etc. For example, if you want to add 1 to a number, you would write:

x += 1


x += (127 - 102)//(5**2)

even though you know that the two expressions are exactly equivalent. 
Even if you know that there is a peep-hole optimizer that ensures that 
the code actually compiled is "x += 1". The intention to the reader is 

This is why, unless performance is *really* critical, one should normally 
write x*2 when multiplying x by 2 rather than x >> 1. (And in Python, the 
overhead means that there is no real performance benefit to using bit 
shifts instead of multiplication or division.)

If your intention is to treat None as a singleton sentinel, not as a 
value, then you ought to use "is" to signal that intention, rather than 
using == even if you know that there won't be any false positives.


More information about the Python-list mailing list