pythonrefcounting

python refcounts


So Python Essential Reference, 4 ed. says:

a = {}
b = {}
a['b'] = b
b['a'] = a
del a
del b

creates a memory leak, and the interpreter need a cycle detection algorithm to delete a and b. However, when I tried to work out how the refcount are, it seems to me that at the end, the refcounts for a and b both go to zero, so no cycle detection algorithms are required. Like:

a = {}
b = {}

refcounts: a = 1, b = 1

a['b'] = b
b['a'] = a

refcounts: a = 2, b = 2

del a

refcounts: b['a'] = 1, b = 1

del b

refcounts: a = 0, b = 0

What is wrong with my understanding of refcounts?


Solution

  • del a does not destory the object pointed to by the variable a, it only removes the variable a from the current namespace. After this, the dict lives on (since the other dict still references it) and therefore still references the second dict b. Likewise, del b does not cause the first dict's refcount to reach zero, because as long as it is alive, it references the second dict, so that one can't be deleted either and keeps the other one alive. Sorry is this sounds confusing, I'm not quite sure how to put this.

    In the end, it looks like this (bulky boxes are objects, arrows are references):

     ┌──────────┐    ┌──────────┐
     │  dict 1  │    │  dict 2  │
     │          │ ◀──┤  key 'a' │
     │  key 'b' ├──▶ │          │
     └──────────┘    └──────────┘