Reference

Steven D'Aprano steve at pearwood.info
Mon Mar 3 22:59:03 EST 2014


On Mon, 03 Mar 2014 17:02:14 -0500, Jerry Hill wrote:

> On Mon, Mar 3, 2014 at 4:51 PM, Tim Chase
> <python.list at tim.thechases.com> wrote:
>> There are a couple use-cases I've encountered where "is" matters:
>>
>> 1) the most popular:
>>
>>   if foo is None:
>>     do_stuff()
> 
> I know this is the one that always comes up, but honestly, I feel like
> "is" doesn't matter here.  That code would be just as correct if it was
> written as:
> 
> if foo == None:
>     do_stuff()
> 
> The only time it would give you a different result from the "is" version
> is if foo was bound to an object that returned True when compared with
> None.  And if that were the case, I'm still not convinced that you can
> tell from looking at those two lines of code which one is buggy, 


It's all about the intention of the code.

Are you trying to test whether an object *is* the None singleton, and no 
other value? Then use "is", don't use == because it is subject to false 
positives (returning True for some objects that aren't actually None).

Or do you want to test whether an object merely happens to have the same 
value as None? Then use == and be glad.

Personally, I have never written code that looks like this:

def spam(a, b=None):
    """Spamify a with optional b.

    If b is None ***OR SOMETHING THAT COMPARES EQUAL TO NONE*** 
    or not supplied, use extra-yummy spammification mode.
    """
    if b == None: ...


But if I ever did want to do that, I can.

Since None is a singleton null-object, something with no state and no 
behaviour, we normally treat it as a sentinel, in which case an identity 
test is usual. I can't really think of any good reason to treat it as a 
value where I would want to use an equality test.


> except
> for the fact that there has been 20 years of custom saying that
> comparing to None with equality is wrong.

It's not *necessarily* wrong, merely wrong the 99.9998% of the time that 
you want to treat None as a sentinel.


-- 
Steven



More information about the Python-list mailing list