1

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.

asked Feb 26, 2020 at 2:56
4
  • 1
    (cpython implementation details) id(x) is the memory address of x so if they had the same ID then they necessarily would be the same object Commented Feb 26, 2020 at 2:58
  • The consequences are the same: it implies they are the same object. Commented Feb 26, 2020 at 3:06
  • @AnthonySottile: The definition of id 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. Commented Feb 26, 2020 at 3:06
  • @AnthonySottile regardless of that implementation detail, 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 Commented Feb 26, 2020 at 3:08

2 Answers 2

5

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.

answered Feb 26, 2020 at 3:05
0

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

answered Feb 26, 2020 at 3:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.