-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGarbageCollection.py
More file actions
executable file
·83 lines (60 loc) · 1.74 KB
/
GarbageCollection.py
File metadata and controls
executable file
·83 lines (60 loc) · 1.74 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 24 18:08:18 2021
@author: maherme
"""
#%%
import ctypes
import gc # This is the garbage collection module
def ref_count(address):
return ctypes.c_long.from_address(address).value
def object_by_id(object_id):
for obj in gc.get_objects():
if id(obj) == object_id:
return "Object exists"
return "Not Found"
# We are going to create a circular reference:
class A:
def __init__(self):
self.b = B(self)
print('A: self: {0}, b: {1}'.format(hex(id(self)), hex(id(self.b))))
class B:
def __init__(self, a):
self.a = a
print('B: self: {0}, a: {1}'.format(hex(id(self)), hex(id(self.a))))
# Disable garbage collector
gc.disable()
# We can check the circular reference:
my_var = A()
print(hex(id(my_var))) # This should be the same as A
print(hex(id(my_var.b))) # This should be the same as B
print(hex(id(my_var.b.a))) # This should be the same as A
#%%
a_id = id(my_var)
b_id = id(my_var.b)
print(hex(a_id))
print(hex(b_id))
print(ref_count(a_id))
print(ref_count(b_id))
print(object_by_id(a_id))
print(object_by_id(b_id))
#%%
# Notice that doing my_var = None the ref_count is 1, this happens because the
# garbage collector is disabled:
my_var = None
print(ref_count(a_id))
print(ref_count(b_id))
print(object_by_id(a_id))
print(object_by_id(b_id))
#%%
# Now we are going to run garbage collector:
gc.collect()
print(object_by_id(a_id))
print(object_by_id(b_id))
print(ref_count(a_id))
print(ref_count(b_id))
# If you rerun this cell several times you will watch a_id and b_id memory
# addresses are different each time, this is due to this memory has been freed.
# So you need to be very careful using memory addresses.
#%%