Python refcounts

So, Python Essential Reference, 4 ed. He speaks:

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

creates a memory leak, and the interpreter needs a loop detection algorithm to remove a and b. However, when I tried to figure out how the recount occurs, it seems to me that in the end, the refcounts for a and b are both zero, so no loop detection algorithms are required. How:

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?

+3
source share
2 answers

del a , a, a . ( ) dict b. del b , refptount , , , dict, . , , , .

, ( - , - ):

+----------+    +----------+
|  dict 1  |    |  dict 2  |
|          | <- |  key 'a' |
|  key 'b' | -> |          |
+----------+    +----------+
+4

Python gc ( 2.3). gc gc - .

+3

Source: https://habr.com/ru/post/1779732/


All Articles