Home > Article > Backend Development > Why do `id({}) == id({})` and `id([]) == id([])` return True in CPython?
CPython's id() function assigns unique identifiers to objects, but this uniqueness is limited to the lifespan of the object. When objects are destroyed, their identifiers become available for reuse.
Consider the following behavior:
<code class="python">tuple1 = () tuple2 = () dict1 = {} dict2 = {} list1 = [] list2 = [] # makes sense, tuples are immutable assert(id(tuple1) == id(tuple2)) # also makes sense dicts are mutable assert(id(dict1) != id(dict2)) # lists are mutable too assert(id(list1) != id(list2)) assert(id(()) == id(())) # why no assertion error on this? assert(id({}) == id({})) # or this? assert(id([]) == id([]))</code>
Why do id({}) == id({}) and id([]) == id([]) return True?
CPython's Memory Allocation
These assertions succeed because of CPython's memory allocation mechanism. When id({}), CPython allocates a dictionary, passes its memory address to id(), and then discards the dictionary. When it's called again, CPython finds a free memory block and reuses the same address. Mutability does not directly affect this behavior.
Code Object Caching
Code objects cache tuples and strings used within a specific function, class, or module. If the same literal (integer, string, or certain tuple) appears multiple times, the same object is reused. Mutable objects are always created at runtime, preventing reuse.
Conclusion
Therefore, an object's id in CPython is unique only during its lifespan. Once an object is destroyed, its id may be reused by other objects. This explains the behavior observed in the provided code snippet.
The above is the detailed content of Why do `id({}) == id({})` and `id([]) == id([])` return True in CPython?. For more information, please follow other related articles on the PHP Chinese website!