Sunday, 15 March 2015

python - finally versus atexit -



python - finally versus atexit -

i end having write , back upwards short python wrapper scripts next high-level structure:

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

notice in except block re-raise exception to script caller sans window-dressing; not problem in particular context. thought here cleanup code should executed means of finally block, exception or not.

am improve off using atexit handler purpose? without level of indentation introduced try.

just utilize contextlib.closing

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

and automatically closed. files objects can used straight contexts don't need closing call.

if close not method used resources, can create custom functions contextlib.contextmanager decorator.

python exception-handling atexit

No comments:

Post a Comment