1

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()
4
  • See related: stackoverflow.com/questions/865115/… Commented Mar 7, 2014 at 10:19
  • To make sure you will never have memory leaks with these type of issues, you can use weakref: docs.python.org/2/library/weakref.html Commented Mar 7, 2014 at 10:24
  • @EdChum thanks, but they don't offer anything appart from a context manager. Commented Mar 7, 2014 at 10:28
  • @Wolph I've read about weakrefs, but I would not know how to implement that in my code. I'd be happy to read a proposal on that. Thanks. Commented Mar 7, 2014 at 10:29

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.