-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
55 lines (40 loc) · 1.15 KB
/
Copy pathexample.py
File metadata and controls
55 lines (40 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""Memory management — reference counting, gc, and weakref."""
import gc
import sys
import weakref
class Node:
def __init__(self, name):
self.name = name
def __del__(self):
print(f" __del__ called for {self.name}")
def ref_count_demo():
obj = Node("alpha")
print(f" refcount: {sys.getrefcount(obj) - 1}") # adjust for getrefcount arg
ref = obj
print(f" after alias: {sys.getrefcount(obj) - 1}")
del ref
del obj
def cyclic_demo():
a = Node("A")
b = Node("B")
a.partner = b
b.partner = a
del a, b
collected = gc.collect()
print(f" gc collected {collected} objects")
def weakref_demo():
obj = ["data"]
weak = weakref.ref(obj)
print(f" weak ref alive: {weak() is not None}")
del obj
print(f" weak ref dead: {weak() is None}")
if __name__ == "__main__":
print("=== Reference counting ===")
ref_count_demo()
print("\n=== Cyclic references + gc ===")
cyclic_demo()
print("\n=== weakref ===")
weakref_demo()
print("\n=== gc stats ===")
print(f" gc enabled: {gc.isenabled()}")
print(f" tracked objects: {len(gc.get_objects()):,}")