Python documentation for id()
function states the following:
This is an 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.CPython implementation detail: This is the address of the object in memory.
Although, the snippet below shows that id
's are repeated. Since I didn't explicitly del
the objects, I presume they are all alive and unique (I do not know what non-overlapping means).
>>> g = [0, 1, 0]
>>> for h in g:
... print(h, id(h))
...
0 10915712
1 10915744
0 10915712
>>> a=0
>>> b=1
>>> c=0
>>> d=[a, b,c]
>>> for e in d:
... print(e, id(e))
...
0 10915712
1 10915744
0 10915712
>>> id(a)
10915712
>>> id(b)
10915744
>>> id(c)
10915712
>>>
How can the id
values for different objects be the same? Is it so because the value 0
(object of class int
) is a constant and the interpreter/C compiler optimizes?
If I were to do a = c
, then I understand c
to have the same id
as a
since c
would just be a reference to a
(alias). I expected the objects a
and c
to have different id
values otherwise, but, as shown above, they have the same values.
What's happening? Or am I looking at this the wrong way?
I would expect the id
's for user-defined class' objects to ALWAYS be unique even if they have the exact same member values.
Could someone explain this behavior? (I looked at the other questions that ask uses of id()
, but they steer in other directions)
EDIT (09/30/2019):
TO extend what I already wrote, I ran python interpreters in separate terminals and checked the id
's for 0
on all of them, they were exactly the same (for the same interpreter); multiple instances of different interpreters had the same id
for 0
. Python2 vs Python3 had different values, but the same Python2 interpreter had same id
values.
My question is because the id()
's documentation doesn't state any such optimizations, which seems misleading (I don't expect every quirk to be noted, but some note alongside the CPython note would be nice)...
EDIT 2 (09/30/2019):
The question is stemmed in understanding this behavior and knowing if there are any hooks to optimize user-define classes in a similar way (by modifying the __equals__
method to identify if two objects are same; perhaps the would point to the same address in memory i.e. same id
? OR use some metaclass
properties)