I am aware that in python, integers from -5 to 256 can have the same ID. However, what are the consequences in the case where two immutable objects have the same ID? How about the consequences when two mutable objects have the same ID?
Thank you.
2 Answers 2
An id
is definitionally unique at a given point in time (only one object can have a given id
at once). If you see the same id
on two names at the same time, it means it's two names referring to the same object. There are no "consequences" to this for immutable types like int
, because it's impossible to modify the object through either alias (x = y = 5
aliases both x
and y
to the same 5
object, but x += 1
is roughly equivalent to x = x + 1
for immutable objects, rebinding x
to a new object, 6
, not modifying the 5
object in place); that's why optimizations like the small int
cache you've observed are safe.
When two mutable objects have the same ID, they reference the same memory address.
a = 10
b = 10
print(id(a), id(b))
Output:
4355009952 4355009952
The only consequence of two mutable objects having the same ID is changing the value in one object will be reflected on the other.
a = 10
b = a
print(a, b)
print(id(a), id(b))
a = 6
print(a, b)
print(id(a), id(b))
Output:
10 10
4338298272 4338298272
6 10
4338298144 4338298272
Immutable objects having the same is not a consequence as they are immutable
id(x)
is the memory address ofx
so if they had the same ID then they necessarily would be the same objectid
requires them to be the same object on any Python implementation. The only implementation detail is the correspondence with the actual memory address, not the guarantee it's the same object.id
guarantees that it will provide a unique identifier for the lifetime of the object, this is true in implentations where it doesn't happen to be the address of the PyObject header