Reference

Jerry Hill malaclypse2 at gmail.com
Tue Mar 4 10:19:22 EST 2014


On Mon, Mar 3, 2014 at 11:52 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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.

In all of the years I've been on this list, I don't think I've seen
more than one or two cases of someone deliberately treating None as a
singleton sentinel.  In most cases, they're either checking the return
value from a function or using it as a default argument to a function
to force some default behavior when no parameter is passed.  I'm
pretty sure you're going to say that the latter use is exactly where
you should us 'is' instead of '=='.  Respectfully, I disagree.

For a beginning python user, identity checking is an attractive
nuisance. The only time most beginners should use it is when comparing
to None.  But, as soon as they are taught that there are two
comparison operators, I start to see 'is' cropping up in more and more
places where they ought to use '=='.  And the problem is that
sometimes it works for them, and sometimes it doesn't.  Sure, students
eventually need to understand the difference between identity and
equality.  My problem is that by enshrining in python custom that the
only correct way to compare to None is with 'is', we have to explain
that concept way early in the teaching process.  I can't count the
number of times that a thread has completely derailed into identity vs
equality, then into interning of strings and small integers, and
suddenly the thread is 40 messages long, and no one has actually
talked about the code that was originally posted beyond that issue.
In approximately zero cases, have I seen code where 'is' versus '=='
actually made any difference, except where the 'is' is wrong.  I've
also never seen the supposedly ever-present boogie man of an object
that mistakenly compares equal to None, much less seen that object
passed to functions with None-based sentinels.

I feel like 'is' is an operator that ought to be saved for an advanced course.

Out of curiosity, do you think we should be doing truth checking with
'is'?  True and False are singletons, and it seems to me that the
justification for idenity versus equality should be just as strong
there, but I don't think I've ever seen anyone even suggest that.

-- 
Jerry



More information about the Python-list mailing list