'is not' or '!='

Skip Montanaro skip at pobox.com
Tue Aug 19 09:12:35 EDT 2014


On Tue, Aug 19, 2014 at 7:42 AM, Martin S <shieldfire at gmail.com> wrote:
>> For example, in CPython 3.4.1:
>>>>> (254 + 3) is 257
>> False
>>>>> (254 + 3) == 257
>> True
>>>>> ('asd' + '@sd') is 'asd at sd'
>> False
>>>>> ('asd' + '@sd') == 'asd at sd'
>> True
>
> Now you have managed to confuse this newbie: What would a valid
> "is-example" look like?

Perhaps adding to the confusion:

>>> (4 + 3) is 7
True

The use of "is" or "is not" is the right thing to do when the object
of the comparison is known to be a singleton. That is true for None.
(I suspect it's true for True and False as well, though for historical
and idiomatic reasons "x is True" is never used.) It would also be
true if you created a sentinel object like this:

SENTINEL = []

then used it to represent "no valid value" in situations where you
can't otherwise assume some value like None is outside the domain of
values:

if mything is not SENTINEL:
    # do whatever is necessary to initialize mything
    ...

The case of "(4 + 3) is 7" simply exposes an optimization in the
implementation of integers in CPython (the small integer cache), and
*must not be relied on*.

Note that

SENTINEL = ()

would be a mistake if () is in the domain of your data, since the
empty tuple is itself a singleton. That is a CPython implementation
detail you shouldn't rely on:

>>> x = ()
>>>
>>> y = (1,2,3)
>>>
>>> z = y[0:0]
>>> z
()
>>> x
()
>>> x == z
True
>>> x is z
True

That's why the first definition of SENTINEL uses the empty list. I can
guarantee that there is no other object in the system which "is" that
particular object.

(Strings which look like identifiers are also "interned" so there is
only one copy in memory. I suspect that's why Chris's string example
included an "@" - to defeat that optimization.)

The CPython runtime is under no obligation to retain these
optimizations. Relying on them is a bug. OTOH, CPython guarantees
there is only one None object in the system.

Skip



More information about the Python-list mailing list