Search code examples
pythonpython-2.7python-2.xcpython

The 'is' operator is not working on objects with the same identity


I'm running:

Python 2.7.8 (default, Oct  6 2017, 09:25:50)
GCC 4.1.2 20070626 (Red Hat 4.1.2-14) on Linux 2

As per the documentation:

The operators is and is not test for object identity: x is y is True if and only if x and y are the same object.

To get an object's identity, we can use the id function.


If we open up a new REPL we can see that 300 and -6 have the same identity (on CPython, this means that both refer to the same memory address):

>>> id(300)
94766593705400
>>> id(-6)
94766593705400

Note that the actual values may differ from execution to execution, but they are always equal.

However, doing 300 is -6 yields False:

>>> 300 is -6
False

I have a couple of questions:

  • Why (and how) do 300 and -6 share the same identity?
  • If they do, why is 300 is -6 yielding False?

Solution

  • After id(300) is executed, no more references to 300 exist, so the id is freed. When you execute id(6), it gets that same chunk of memory and stores 6 instead. When you do -300 is 6, -300 and 6 are both referenced at the same time, so they won't have the same address anymore.

    If you keep references to both -300 and 6, this happens:

    >>> a, b = -300, 6
    >>> id(a)
    some number
    >>> id(b)
    some different number; 6 is still in the other memory address.
    

    Note: In CPython, numbers from -5 to 256 (I think) are cached, and will always have the same address, so this will not happen.