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
.
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.