Sub topic 1
Why cleanup needs a guarantee: try/finally and its limits
Programs borrow things from the operating system and from other programs: file handles, network sockets, database connections, locks. Each one must be given back. This chapter shows why "remember to clean up" is not enough, how try/finally provides a real guarantee, and where that tool becomes awkward. The rest of the tutorial builds on those limits.
Prerequisites
This chapter assumes you can:
- Write Python functions and classes.
- Use
try,except, andfinally, and you know that exceptions travel up the call stack until something catches them. - Read and write files with
open().
You do not need generators, decorators, or anything from contextlib yet. Later chapters cover them.
Resources that must be released
A resource is anything that is limited in supply and must be returned after use. Common examples:
| Resource | What happens if it is not released |
|---|---|
| File handle | The operating system limits open files per process. Buffered data may never reach the disk. |
| Socket | The connection stays open and the port or peer is tied up. |
| Database connection | The pool runs dry and new requests wait or fail. |
| Lock | Other threads block forever (a deadlock). |
| Temporary state, such as the current directory | Later code runs in the wrong environment. |
Every one of these has the same shape: acquire, use, release. The release step must run no matter how the "use" step ends.
The unguarded version
Here is the obvious way to write it:
def first_line(path):
f = open(path)
line = f.readline()
if not line:
return None # early return: close() is skipped
f.close()
return line.strip()There are two ways to lose the close call. The early return None skips it. And if readline() raises, for example UnicodeDecodeError on a badly encoded file, the exception leaves the function before f.close().
In CPython the file object is usually closed anyway, because its reference count drops to zero when the function ends. You should not depend on that. Other Python implementations close the file only when the garbage collector runs. CPython can also keep the object alive, for instance inside a traceback that something is holding. Python emits a ResourceWarning for files that were left to the garbage collector. Warnings of that kind are hidden by default and show up when you run with python -W default.
The real problem is that the code is correct only on the paths you thought about.
try/finally: the guarantee
A finally block runs when the try block finishes, whatever the reason. That includes normal completion, an exception, and return, break, or continue.
def first_line(path):
f = open(path)
try:
line = f.readline()
return line.strip() or None
finally:
f.close()The next example makes the ordering visible. Run it to see that finally executes before the return value reaches the caller:
def demo(fail):
print("acquire")
try:
if fail:
raise RuntimeError("boom")
return "result"
finally:
print("release")
print(demo(False))
try:
demo(True)
except RuntimeError as exc:
print("caught", exc)The output is acquire, release, result, then acquire, release, caught boom. In both cases release is printed before the caller sees the outcome.
This is the guarantee the chapter title refers to. The cleanup code sits in one place, and Python promises to run it.
Limit 1: where you put the acquire matters
A common mistake is to put the acquisition inside the try:
f = None
try:
f = open("missing.txt")
data = f.read()
finally:
f.close()If open() fails with FileNotFoundError, f is still None. The finally block then calls None.close(), which raises AttributeError. That error is the one the user sees at the bottom of the traceback. The real cause appears above it, under "During handling of the above exception, another exception occurred". If you leave out the f = None line, you get NameError instead, which is no better.
The rule is to acquire before the try, so that the finally block runs only for resources you actually hold:
f = open("missing.txt") # failure here needs no cleanup
try:
data = f.read()
finally:
f.close()This is easy to get wrong, and nothing in the language warns you.
Limit 2: several resources produce nesting
Each resource needs its own try/finally, and each one must be acquired after the previous try has begun. Here is a file copy:
def copy(src_path, dst_path):
src = open(src_path, "rb")
try:
dst = open(dst_path, "wb")
try:
dst.write(src.read())
finally:
dst.close()
finally:
src.close()Why not open both files first, then use one try? Because if the second open() fails, the first file is never closed. Why not close both in one finally? The next limit explains that.
With three or four resources the code drifts to the right, and the real work is buried at the deepest level.
Limit 3: cleanup code can fail too
The close() call can raise. Flushing buffered data to a full disk is a typical cause. This causes two problems.
First, an exception raised in finally replaces the exception that was already in flight. The original is not lost entirely. Python attaches it as __context__ on the new one. But the code that catches the exception now sees the cleanup error, not the original failure:
class Flaky:
def close(self):
raise OSError("close failed")
r = Flaky()
try:
try:
raise ValueError("body failed")
finally:
r.close()
except OSError as e:
print("caught:", e)
print("context:", repr(e.__context__))The output is caught: close failed followed by context: ValueError('body failed'). A handler written as except ValueError would never run.
Second, if you put two cleanup calls in one finally block, a failure in the first stops the second:
finally:
first.close() # if this raises...
second.close() # ...this never runsThat is why the copy example above nests its blocks instead of using one flat finally.
Limit 4: acquire and release are far apart
In the unguarded code the open() call is at the top of the function and the close() call is at the bottom. A reader must scan everything in between to confirm the pairing. In a long function, a new return added later can sit outside the try and bypass cleanup, because the guarantee covers only code inside the block.
There is also repetition. Every function that opens a connection repeats the same four lines. Copies drift apart, and one of them eventually gets the order wrong.
Summary of limits
| Limit | Symptom | Cause |
|---|---|---|
| Acquire inside `try` | `AttributeError` or `NameError` hides the real error | `finally` runs for a resource that was never acquired |
| Several resources | Deep nesting | One `try`/`finally` per resource |
| Failing cleanup | The original exception is replaced; later cleanup is skipped | An exception raised inside `finally` |
| Distance and repetition | Easy to forget or misplace | Acquire and release are written by hand each time |
What comes next
try/finally gives the guarantee, and what is missing is a way to package it. You want to write "acquire, use, release" once, name it, and reuse it with no chance of putting the acquire in the wrong place. Python's answer is the with statement, which the next chapter introduces. Here is the file example in its final form, to preview the shape:
with open("data.txt", "w") as f:
f.write("hello")Everything in this chapter still applies underneath. The with statement compiles down to the same guarantee, and the later chapters on __exit__ show how it handles the failure cases above.
Exercise
This function is meant to always close the connection, but it has a bug that appears when connect() raises an error. Name the bug and rewrite the function.
def query(connect, sql):
conn = None
try:
conn = connect()
return conn.execute(sql)
finally:
conn.close()
Show answer
When connect() raises, conn is still None, so conn.close() raises AttributeError and hides the real connection error. Acquire before the try:
def query(connect, sql):
conn = connect()
try:
return conn.execute(sql)
finally:
conn.close()
Now finally only runs when a connection exists, and a failed connect() propagates unchanged.
Exercise
In the code below, a.close() raises an exception. Does b.close() run? Which fix guarantees both are attempted?
try:
work()
finally:
a.close()
b.close()
Show answer
No. The exception from a.close() leaves the finally block immediately, so b.close() is skipped. Give each resource its own try/finally, so that b is closed even when closing a fails:
a = opena()
try:
b = openb()
try:
work()
finally:
b.close()
finally:
a.close()