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): self.close()
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): self.name = name def __del__(self): print '%r got deleted' % self def __repr__(self): return '<%s:%s>' % (self.__class__.__name__, self.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