Python __del__ not called on exception
<p>I'm attempting to wrap a poorly written Python module (that I have no control of) in a class. The issue is that if I don't explicitly call that module's close function then the python process hangs on exit, so I've attempted to wrap the module with a class that has a <strong>del</strong> method, however the <strong>del</strong> method does not seem to be called on exceptions.</p>

<p>Example:</p>

<pre><code>class Test(object):
    def __init__(self):
        # Initialize the problematic module here
        print "Initializing"

    def __del__(self):
        # Close the problematic module here
        print "Closing"

t = Test()
# This raises an exception
moo()
</code></pre>

<p>In this case <strong>del</strong> is not called and python hangs. I need somehow to force Python to call <strong>del</strong> immediately whenever the object goes out of scope (like C++ does).
Please note that I have no control over the problematic module (i.e. cannot fix the bug that causes this in the first place) and also no control over whoever uses the wrapper class (can't force them to use "with" so I can't use <strong>exit</strong> either).</p>

<p>Is there any decent way to solve this?</p>

<p>Thanks!</p>