8000 Messing around with garbage collection with circular references · anubhavcoder/practice-python@f6802ef · GitHub
[go: up one dir, main page]

Skip to content

Commit f6802ef

Browse files
committed
Messing around with garbage collection with circular references
and the gc and sys modules.
1 parent b0ff81c commit f6802ef

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

experiments/garbage_collection.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
Messing around with garbage collection with circular references
3+
and the gc and sys modules. Sys provides getrefcount()
4+
"""
5+
6+
import gc
7+
import sys
8+
9+
10+
def main():
11+
a = 4
12+
b = 5
13+
14+
c_list = []
15+
c_list.append(123)
16+
c_list.append(456)
17+
# reference cycle
18+
c_list.append(c_list)
19+
c_list[2].append(789)
20+
21+
# foo = ['hi']
22+
# c_list = foo
23+
24+
print(c_list)
25+
26+
print("Stats: {}".format(gc.get_stats()))
27+
print("Count: {}".format(gc.get_count()))
28+
print("GC enabled: {}".format(gc.isenabled()))
29+
print("Threshold: {}".format(gc.get_threshold()))
30+
print("c_list is tracked: {}".format(gc.is_tracked(c_list)))
31+
32+
"""
33+
The count returned is generally one higher than you might expect,
34+
because it includes the (temporary) reference as an argument to getrefcount().
35+
"""
36+
print("Reference count for c_list: {}".format(sys.getrefcount(c_list)))
37+
del c_list[2]
38+
print("Reference count for c_list: {}".format(sys.getrefcount(c_list)))
39+
40+
print("Collecting: {}".format(gc.collect()))
41+
42+
print("Done.")
43+
44+
45+
if __name__ == "__main__":
46+
main()

0 commit comments

Comments
 (0)
0