Slide 34
Slide 34 text
gc module
We can use the ctypes foreign function library to expose ob_refcnt for lost
Python objects
import ctypes
import gc
# disable garbage collection
gc.disable()
# use ctypes to map PyObject internal struct
class PyObject(ctypes.Structure):
_fields_ = [('ob_refcnt', ctypes.c_ssize_t)]
# create a cyclical reference
obj_1, obj_2 = {}, {}
obj_1['next'], obj_2['next'] = obj_2, obj_1
# save objs addresses
obj_1_addr, obj_2_addr = id(obj_1), id(obj_2)
# unbind obj_1 and obj_2 references
del obj_1, obj_2
# prove that refcounts are not 0 due to cyclical reference
print(f'obj_1 refcnt: '
'{PyObject.from_address(obj_1_addr).ob_refcnt}')
print(f'obj_2 refcnt: '
'{PyObject.from_address(obj_2_addr).ob_refcnt}')
Slide 34 of 97