Circular references

You can cause a memory leak in Python by creating circular references, or by never deleting the last reference to an object. The latest versions of Python support a garbage collector that can detect circular references and clean them up. It's quite difficult to create circular references, but it's very easy to accidentally keep references lying about. The next snippet shows the circularity of referring from A to B to A...

Example 9-2. circular.py - circululululular references

#
# circular.py - circululululular references in Python
#
class B: pass

class A:

    def __init__(self):
        self.b=B()
        self.b.a=self

a=A()

print a
print a.b
print a.b.a
print a.b.a.b.a.b.a.b.a.b.a.b.a.b.a.b.a.b.a.b.a.b.a
      
boudewijn@maldar:~/doc/opendoc/ch3 > python circular.py
<__main__.A instance at 0x8199bb4>
<__main__.B instance at 0x8199c04>
<__main__.A instance at 0x8199bb4>
<__main__.A instance at 0x8199bb4>
    

If you delete the instance a, you only make the objects inaccessible; because b still refers to a, there's a reference for the reference counter, and a will not be destroyed. Thus b will not be destroyed either, which means the reference to a remains in existence — ad infinitum! (Or at least until the Python interpreter shuts down.)