Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python __del__ not called on exception

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 del method, however the del method does not seem to be called on exceptions.

Example:

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()

In this case del is not called and python hangs. I need somehow to force Python to call del 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 exit either).

Is there any decent way to solve this?

Thanks!

like image 599
Dan Avatar asked May 24 '26 23:05

Dan


1 Answers

If you want some resource to be released on an exception, think about __enter__ + __exit__ paradigm.

class Test(object):
    def __enter__(self):
        pass

    def __exit__(self):
        pass  # Release your resources here

with Test() as t:
    moo()

When the execution goes into the 'with' block, the method __enter__() of 't' is called, and then it leaves the block due to either normal flow, or an exception, the method __exit__() of 't' is called.

like image 138
Dmitry T. Avatar answered May 26 '26 12:05

Dmitry T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!