Python use destructor in a memory safe way

I have a class that represents a database connection, that has a close method. To make it more comfortable to use, the class itself is a context manager that closes the connection when finished working with it.

The problem is that I got no guarantee that the user of this class will always remember to either use the context manager or close it explicitly, so I would like to implement a method to be called when the object is garbage collected.

The __del__ method looks pretty much like what I need, but I have read in many places that it is risky since it can disturb the garbage collector, especially if there are some circular references.

How true is that? will the following code entail some potential memory leaks?

def __del__(self):


Here's an example where you would need the weakref so the child doesn't block the parent from cleaning up:

import weakref

class Spam(object):
    def __init__(self, name): = name

    def __del__(self):
        print '%r got deleted' % self

    def __repr__(self):
        return '<%s:%s>' % (self.__class__.__name__,

class SpamChild(Spam):
    def __init__(self, name, parent):
        Spam.__init__(self, name)
        self.parent = weakref.ref(parent)

    def __del__(self):
        print '%r, child of %r got deleted' % (self, self.parent)

a = Spam('a')
b = SpamChild('b', a)
del a

Need Your Help

Getting first key-value pair from Map without using <c:forEach>

jsp jstl el

How do I get the first key-value pair from a Map without using &lt;c:forEach&gt;?

DTS Packages & a Connection to Access

ms-access connection dts

Using DTS I'm dynamically creating an access database. After the file is created (which works at this point) I'm having the DTS package post it via HTTP to another site. (This HTTP is just how it h...