30

Why does CPython (no clue about other Python implementations) have the following behavior?

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([]))

I have a few ideas why it may, but can't find a concrete reason why.

EDIT

To further prove Glenn's and Thomas' point:

[1] id([])
4330909912
[2] x = []
[3] id(x)
4330909912
[4] id([])
4334243440
5
  • 1
    Wow, that is weird. It looks like if you get the id if a new dict/list, and then let its reference count drop to zero, and then get another new dict/list it'll have the same id. It looks like an unmodified dict/list is saved for later when its reference count drops to zero. My guess is that this is an optimization for the case where code that creates and immediately discards dicts/lists. This is pretty common, eg: code that uses setdefault often does this. Oct 6, 2010 at 22:10
  • @Potatoswatter: Definitely not. The ID of an object never changes after it's created, and lists and dicts are mutable objects, so empty lists and dicts can not be memoized in the way that strings and small numbers are. Oct 6, 2010 at 22:11
  • @Glenn Maynard: technically, you can memoize empty list and dict by first emptying them before discarding; however, that's probably just a waste of processor cycle compared to creating a new one.
    – Lie Ryan
    Oct 6, 2010 at 22:34
  • @Lie Ryan: I don't really know what you're saying, but you can't memoize the empty list, because the id of an object must remain constant for its lifetime. Oct 6, 2010 at 22:55
  • @Glenn Maynard: yes you can. Technically, you can have a pool of empty lists and empty dicts; every time you need a new dict, this pool is checked, and every time you dispose of a list (i.e. when the refcount is zero) you put the list/dict back into the pool. There is no requirement that two objects in two different times does not have the same id(). However, there isn't very much savings to be had here. I just realized, this isn't memoization, but caching
    – Lie Ryan
    Oct 6, 2010 at 23:05

2 Answers 2

45

When you call id({}), Python creates a dict and passes it to the id function. The id function takes its id (its memory location), and throws away the dict. The dict is destroyed. When you do it twice in quick succession (without any other dicts being created in the mean time), the dict Python creates the second time happens to use the same block of memory as the first time. (CPython's memory allocator makes that a lot more likely than it sounds.) Since (in CPython) id uses the memory location as the object id, the id of the two objects is the same. This obviously doesn't happen if you assign the dict to a variable and then get its id(), because the dicts are alive at the same time, so their id has to be different.

Mutability does not directly come into play, but code objects caching tuples and strings do. In the same code object (function or class body or module body) the same literals (integers, strings and certain tuples) will be re-used. Mutable objects can never be re-used, they're always created at runtime.

In short, an object's id is only unique for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id.

0
42

CPython is garbage collecting objects as soon as they go out of scope, so the second [] is created after the first [] is collected. So, most of the time it ends up in the same memory location.

This shows what's happening very clearly (the output is likely to be different in other implementations of Python):

class A:
    def __init__(self): print("a")
    def __del__(self): print("b")

# a a b b False
print(A() is A())
# a b a b True
print(id(A()) == id(A()))
5
  • So why does print id({}); a = []; print id({}) print the same value twice in cpython? Shouldn't that list being stored in a take up the spot freed up by the first dict? Nov 2, 2010 at 21:52
  • 3
    @Laurence: No, not necessarily. Allocators are complex and heavily optimized; they don't simply take the first address available. In this case, the dict object and the list object have very different sizes, which probably puts them into different allocation buckets. Nov 2, 2010 at 22:37
  • 1
    In Python 3.x, the way the allocators work (at the high level) is a documented part of the the C API rather than buried in comments in the source, although I think the specific custom list and dict/set allocators and freelists are only documented in the source (Objects/listobject.c and dictobject.c).
    – abarnert
    May 27, 2015 at 4:11
  • Another way to see this is this snippet: x = []; i = id(x); del x; gc.collect(); i == id([]) . If you drop the gc.collect() call this will (likely) return False, otherwise (likely) True.
    – filmor
    Dec 9, 2015 at 10:48
  • 1
    @filmor that's not how CPython garbage collection works Sep 2, 2017 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.