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