Question

I end up having to write and support short python wrapper scripts with the following high-level structure:

try:
    code
    ...
    ...
except:
    raise
finally:
    file_handle.close()
    db_conn.close()

Notice that all I do in the except block is re-raise the exception to the script caller sans window-dressing; this is not a problem in my particular context. The idea here is that cleanup code should always be executed by means of the finally block, exception or not.

Am I better off using an atexit handler for this purpose? I could do without the extra level of indentation introduced by try.

Was it helpful?

Solution 2

Just use contextlib.closing

with closing(resource1) as f1, closing(resource2) as f2:
    f1.something()
    f2.something()

And they will be automatically closed. Files objects can be used directly as contexts so you don't need the closing call.

If close is not the only method used by your resources, you can create custom functions with the contextlib.contextmanager decorator.

OTHER TIPS

The atexit module provides a simple interface to register functions to be called when a program closes down normally. Functions registered are automatically executed upon normal interpreter termination.

import atexit

def cleanup():
    print 'performimg cleanup'

# multiple functions can be registered here...    
atexit.register(cleanup)

The sys module also provides a hook, sys.exitfunc, but only one function can be registered there.

Finally is accompanied by try except block, functionality of finally can also be used for something similar like cleanup, however at finally block sys.exc_info is all-None.

If the finally clause raises another exception, the saved exception is discarded however you can put try except in the function registered with atexit to handle them.

Another pro-con is atexit functions are only executes when program terminates, however you can use finally (with try-except) anywhere in the code and perform the cleanup

In you scenario, where you want to raise an exception from cleanup content, usage of atexit would be helpful, if you are ok for cleanup to happen at the end of the program

atexit is called upon program termination, so this is not what you are looking for.

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