Python try finally: Cleanup Code That Always Runs
Python's try finally runs clean-up code every time: the finally block runs when the try block finishes and also when it raises an error.
You need try and except and Python Context Managers. This lesson shows finally with no except, and how it makes a context manager clean up after an error in its with block.
finally runs whether or not there is an error
A try block can have a finally block and no except. The function below is called once with text that works and once with text that raises ValueError.
def read_score(text): try: print("Score:", int(text)) finally: print("Finished reading", text)read_score("12")try: read_score("twelve")except ValueError as error: print("Caught:", error)Both calls print Finished reading. For "twelve", int() raises, so the Score: line is skipped, and the finally block still runs.
finally does not catch the error. After the finally block, the error carries on to the code that called read_score. There the except catches it, so Caught: comes after Finished reading twelve. Without that outer try, the program would stop with the error right after the finally line.
finally versus except: except handles an error and stops it. finally runs clean-up and lets the error go on. Use finally for clean-up that must happen either way, and leave the error to code that knows what to do with it.
finally versus a line after the try: a line after the whole try statement runs only when nothing raised. A line in finally runs every time.
Without finally, a context manager skips its clean-up
This context manager changes a value. Before its with block, busy.append(name) adds a name to the list busy. After the block, busy.remove(name) takes it out again. The second with block raises an error, which is caught outside.
from contextlib import contextmanagerbusy = []@contextmanagerdef working(name): busy.append(name) yield busy.remove(name)with working("Ada"): print("Inside:", busy)print("After:", busy)try: with working("Sam"): print("Inside:", busy) raise ValueError("printer jammed")except ValueError as error: print("Caught:", error)print("After:", busy)For Ada, the list is empty again after the block. For Sam, the last line prints After: ['Sam'].
Here is why. The function pauses at yield while the with block runs. When the block raises, @contextmanager raises the same error inside the function, at the yield line. Nothing catches it there, so the rest of the function never runs and busy.remove(name) is skipped. The error then leaves the with statement, and the except outside catches it.
The raise ValueError(...) line stands in for any error in a real block, such as a failed int().
Put yield inside try and finally
The fix: do the set-up, then put yield inside try and the clean-up inside finally.
from contextlib import contextmanagerbusy = []@contextmanagerdef working(name): busy.append(name) try: yield finally: busy.remove(name)try: with working("Sam"): print("Inside:", busy) raise ValueError("printer jammed")except ValueError as error: print("Caught:", error)print("After:", busy)Now the last line prints After: []. The error comes out at yield, inside try, so finally removes Sam. Then the error carries on, and the except outside the with block prints Caught: printer jammed. A block that finishes runs finally too, so Ada's block from above still works.
Keep the set-up above try. If the set-up itself fails, the block never runs and there is nothing to clean up.
Note: Do not add an except to the context manager just to be safe. If it catches the error and does not raise it again, the with statement hides the error: the code outside never hears about it. with open() works like the fixed working: the file is closed even when the block raises.
The busy list stands in for real set-up you must undo, such as a lock or a network connection. This lesson leaves those out, and it does not mix except and finally in one try.
See also: Python Try Except, Python Context Managers.
Your turn
Write borrowed(book) with @contextmanager. It takes book off shelf before its with block and puts it back on the end of shelf afterwards. The block below fails on int("lots"), and the book must still come back.
On the shelf: ['Dictionary', 'Novel'] Could not count the pages Back on the shelf: ['Dictionary', 'Novel', 'Atlas']
from contextlib import contextmanagershelf = ["Atlas", "Dictionary", "Novel"]# write borrowed(book): remove book from shelf before the block, append it back after, even after an errortry: with borrowed("Atlas"): print("On the shelf:", shelf) pages = int("lots")except ValueError: print("Could not count the pages")print("Back on the shelf:", shelf)