Why do these statements evaluate the way they do?

Chris Angelico rosuav at gmail.com
Sat May 7 04:18:07 EDT 2016


On Sat, May 7, 2016 at 5:49 PM, Stephen Hansen <me at ixokai.io> wrote:
> The long and short of it is: you should almost never use 'is' for
> comparing integers (or strings). It doesn't mean what you think it does
> and isn't useful to you. Compare equality.
>
> In general, the only things you should use 'is' for is when comparing to
> singletons like None, True or False (And consider strongly not comparing
> against False/True with is, but instead just 'if thing' and if its True,
> it passes).
>
> Otherwise, 'is' should only be used when you're comparing *object
> identity*. You don't need to do that usually. Only do it when it matters
> to you that an object with value A might be equal to an object of value
> B, but you care that they're really different objects.

Equality sometimes is immaterial; there are times when you want to
know whether this object you got back is the same one that was sent
in, and equality's out of the question. (It's funny how there's this
parallel thread about "equal opportunity", in which gender equality is
the focus. In this thread, equality really CAN be irrelevant.) For
example, to adequately distinguish between "argument omitted" and
"some argument was provided", this idiom is commonly used:

_SENTINEL = object()
def next(iterator, default=_SENTINEL):
    try:
        return iterator.__next__()
    except StopIteration:
        if default is _SENTINEL: raise
        return default

It makes no difference whatsoever whether the default might compare
equal to something; all that matters is: "Is this the sentinel?". And
this check is faster and safer than equality, anyway.

But with integers and strings, always do equality checks. (Interned
strings can safely be identity-checked, which would be faster in the
case where they're unequal, but that's a micro-optimization that's
safe ONLY if both strings have definitely been interned, so it's
better not to bother.)

ChrisA



More information about the Python-list mailing list