[Doc-SIG] Does the "is" operator only matter for mutable object?

Laura Creighton lac at openend.se
Mon Mar 7 00:08:38 CET 2011


I've been doing more thinking, and I think the problem is more deeply 
rooted than this.

  From the original doc:

> The operators is and is not compare whether two objects are really the same
> object;
> this only matters for mutable objects like lists.

This is actually wrong.  If x is y, then you _aren't_ comparing two
objects, you are comparing one object with itself, and that is the
whole point.  You are comparing two names, and seeing if they are
bound to the same object.  What I really want to tell the perplexed
to do is read: http://effbot.org/zone/python-objects.htm  However:

Given that this is in the section on comparing sequences and other
types:

The operators ``is`` and ``is not`` test for object identity.  If two
different names are bound to the same object, then they compare the
same:  ``x is y`` .  

>>> v = [1,2,3]
>>> w = v
>>> v is w
True
>>> v.append(4)
>>> v
[1, 2, 3, 4]
>>> w
[1, 2, 3, 4]

Confusion arises because implementors are free to cache immutable objects
with the same value and type to the same object for reasons of efficiency.

[PyPy 1.4.1] 
Type "help", "copyright", "credits" or "license" for more information.

>>>> w = 1
>>>> y = 1
>>>> w is y
False

Python 2.6.6 #(I don't have a 3.x around , I assume it works the same way)
Type "help", "copyright", "credits" or "license" for more information.
>>> w = 1
>>> y = 1       
>>> w is y  # this might surprise you
True

Testing the object identity of unmutable objects with the ``is``
or ``is not`` operators is rarely something you want to do, because the
result is implementation dependent. 

Singleton objects such as ``True``, ``False``, and ``None`` are always 
the same object.  The canonical way to test whether an object is 
a singleton is to test for object identity, not equality.  So

>>> if x is None:
    ... do something ...

not

>>> if x == None:
    ... do something ...

--------------
I think this will fix the confusion, but maybe it belongs someplace
other than the comparing sequence section. 
http://docs.python.org/py3k/tutorial/datastructures.html#comparing-sequences-and-other-types


More information about the Doc-SIG mailing list