开发者

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 开发者_StackOverflow中文版of refcounts?


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' ├──▶ │          │
 └──────────┘    └──────────┘


Python has had cyclic gc for some time now (since 2.3). However it's possible to import the gc module and tune the cyclic gc - including the possibility of disabling it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜