Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 524
Matias Cicero Avatar asked Dec 02 '22 11:12

Matias Cicero


2 Answers

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.

like image 179
internet_user Avatar answered Dec 04 '22 07:12

internet_user


This is documented behavior of the id() function:

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

The lifetime of an integer object in the sample code is just the function call (e.g. id(300)) as no other references to it exist.

like image 40
Eugene Yarmash Avatar answered Dec 04 '22 09:12

Eugene Yarmash