Skip to content

Instantly share code, notes, and snippets.

@alastairparagas
Last active July 28, 2018 15:56
Show Gist options
  • Save alastairparagas/08253e0ef385174849d41162cf9e09dc to your computer and use it in GitHub Desktop.
Save alastairparagas/08253e0ef385174849d41162cf9e09dc to your computer and use it in GitHub Desktop.
Python-based Garbage Collection
import gc
import ctypes
gc.set_debug(gc.DEBUG_SAVEALL)
class PyObject(ctypes.Structure):
_fields_ = [("refcnt", ctypes.c_long)]
object1 = {}
object2 = {}
object3 = {}
object1['reference_to_2'] = object2
object2['reference_to_1'] = object1
object3['some_key'] = 1
object1_memory_address = id(object1)
object2_memory_address = id(object2)
object3_memory_address = id(object3)
print "Before garbage collection --->"
print "Refcount for object1: {count}".format(
count=PyObject.from_address(object1_memory_address).refcnt
)
print "Refcount for object2: {count}".format(
count=PyObject.from_address(object2_memory_address).refcnt
)
print "Refcount for object3: {count}".format(
count=PyObject.from_address(object3_memory_address).refcnt
)
del object1, object2, object3
gc.collect()
print "After garbage collection --->"
print "Refcount for object1: {count}".format(
count=PyObject.from_address(object1_memory_address).refcnt
)
print "Refcount for object2: {count}".format(
count=PyObject.from_address(object2_memory_address).refcnt
)
print "Refcount for object3: {count}".format(
count=PyObject.from_address(object3_memory_address).refcnt
)
print "Objects that cannot be cleaned up by reference counting: --->"
for x in gc.garbage:
print x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment