Question

I use a with statement with the following class.

def __init__(self):
    ...

def __enter__(self):
    return self

def __exit__(self, type, value, traceback):
    print "EXIT Shutting the SDK down"
    ret = self.sdkobject.ShutDown()
    self.error_check(ret)

This catches any error that occur when I am using the object of the class and safely shuts down the SDK that I am using. However, it catch problems when the class is still initializing. I have recently found the "del" function which neatly solves this problem. However, it can't be used in conjunction with the exit function (as the with statement evokes the exit and the del gets an exception). How can I set up a destructor using a with statemtent, which will catch failures even during initialization?

Was it helpful?

Solution 2

Create a separate shutdown function that gets called in the try/except block of the __init__ and wherever else you need a proper shutdown.

OTHER TIPS

Exceptions in the __init__ need to be dealt with directly in that method:

class YourContextManager(object):
    sdkobject = None

    def __init__(self):
        try:
             self._create_sdk_object()
        except Exception:
             if self.sdkobject is not None:
                 self.sdkobject.ShutDown()
             raise

    def _create_sdk_object(self):
        self.sdkobject = SomeSDKObject()
        self.sdkobject.do_something_that_could_raise_an_exception()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        print "EXIT Shutting the SDK down"
        ret = self.sdkobject.ShutDown()
        self.error_check(ret)

Note that the exception is re-raised; you want to give the consumer of the context manager an opportunity to handle the failure to create a context manager.

Catch the exception in __init__ and handle it. __del__ is unnecessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top