Why don't tuples get the same ID when assigned the same values?

纵然是瞬间 提交于 2019-12-24 10:35:38

问题


When I executed the following steps, both tuples (a and b) haven't retained their original IDs even when I reassigned older values ((1,2)).

>>> a , b = (1,2) , (1,2)
>>> a
(1, 2)
>>> b
(1, 2)
>>> id(a) , id(b)
(80131912, 91541064)
>>> a , b = (3,4) , (3,4)
>>> a
(3, 4)
>>> b
(3, 4)
>>> id(a) , id(b)
(91559048, 91689032)
>>> a , b = (1,2) , (1,2)
>>> a
(1, 2)
>>> b
(1, 2)
>>> id(a) , id(b)
(91556616, 91550408)

But in the following case, both have gotten their older IDs back.

>>> a = (1,2)
>>> b = (1,2)
>>> a , b
((1, 2), (1, 2))
>>> id(a)
88264264
>>> id(b)
88283400
>>> a = (3,4)
>>> b = (3,4)
>>> id(a)
88280008
>>> id(b)
88264328
>>> a = (1,2)
>>> b = (1,2)
>>> id(a)
88264264
>>> id(b)
88283400
>>> a , b
((1, 2), (1, 2))
>>> id(a) , id(b)
(88264264, 88283400)

Can someone please explain this?


回答1:


You created new tuple objects. That they have the same contents doesn't mean that they'll be the exact same tuple objects in memory.

Immutability doesn't mean that creating the same value will create the same object. You never mutated the old (1, 2) tuples, and your new (1, 2) tuples are not mutable either.

CPython does keep a cache of re-usable tuple objects (so it doesn't have to create new objects all the time, Python goes through a lot of small tuples during a typical program), but that's an implementation detail you can't rely on. It is this cache that is the reason for the same ids being seen again, for tuples of length two. See How is tuple implemented in CPython? if you want to know how the cache is implemented.

Furthermore, in CPython, id() is the memory location of the object, and Python is free to re-use memory locations once old objects have been freed. This is clearly documented:

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.

It is always possible to see the same id() value for new objects. Sometimes this means you still have the same object (as is the case for small integers or tuples or certain types of string object), sometimes it is just that the interpreter re-used the same location in memory. You should never rely on this, these are implementation details for performance purposes and subject to change.



来源:https://stackoverflow.com/questions/49327859/why-dont-tuples-get-the-same-id-when-assigned-the-same-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!