« Back to Index

[Python Garbage Collection Circular References]

View original Gist on GitHub

Tags: #python #gc #memory

gc-circular-reference.py

import gc

gc.set_debug(gc.DEBUG_SAVEALL)  # gc.collect saves to gc.garbage instead of deleting.

class A(object):
    ref = None

a = A()
a.ref = a  # circular reference created
del a  # only __main__ reference is deleted

gc.collect()
# >>> 2 - 2 references were collected

gc.garbage
# >>> [<__main__.A object at 0x29ce750>, {'ref': <__main__.A object at 0x29ce750>}]