Sub topic 1
Why Cleanup Needs a Guarantee: try/finally and Its Limits
Prerequisites
This chapter assumes you can already do the following:
- Write Python functions and call methods on objects.
- Read and write files with
open(). - Use
try,except, andfinally.
You do not need to know generators or decorators yet. Later chapters use them.
The problem: resources must be released
Some objects hold something outside your program: an open file, a lock, a database connection, a network socket. The operating system limits how many of these can exist at once. If you don't release one, you get a leak. Files may stay locked, buffered data may never reach the disk, and a long-running program may eventually fail with "too many open files".
Here is the obvious way to write a file:
f = open("data.txt", "w")
f.write("hello")
f.close()This works only if nothing goes wrong. If f.write() raises an exception, such as a full disk, Python skips f.close(). The cleanup depends on the happy path.
try/finally gives the guarantee
A finally block runs when the try block finishes in any way. That includes normal completion, an exception, return, break, and continue.
f = open("data.txt", "w")
try:
f.write("hello")
finally:
f.close()The exception is not swallowed. After finally runs, it continues up the call stack. You get cleanup without hiding errors.
Where try/finally falls short
try/finally is correct, but it has costs that grow with the size of your program.
Acquisition placement is easy to get wrong
Putting open() inside the try looks natural, but it is a bug:
try:
f = open("missing/dir/data.txt", "w") # raises FileNotFoundError
f.write("hello")
finally:
f.close() # NameError: f was never assignedThe NameError in finally replaces the real FileNotFoundError in what the user sees. Python does attach the original as context, but the traceback now points at the wrong problem. The acquisition must come before the try, and you have to remember that every time.
Several resources nest
Copying one file into another needs two cleanups. Each resource needs its own try/finally, so that if opening the second fails, the first is still closed:
src = open("in.txt")
try:
dst = open("out.txt", "w")
try:
dst.write(src.read())
finally:
dst.close()
finally:
src.close()Three resources mean three levels of nesting. The real work, one line, is buried in the structure.
Setup and cleanup are far apart
The open() call and the close() call sit on opposite sides of the body. In a long body, a reader must scan to confirm that cleanup exists. A reviewer cannot tell at a glance whether a given acquisition is protected.
Nothing enforces the pattern
Nothing forces anyone to write the finally. The code without it runs fine in testing and leaks only under failure, which is the hardest time to notice. Each caller must repeat the pattern correctly. The class that owns the resource cannot require it.
Cleanup can raise too
If close() itself raises inside finally, the new exception replaces the one that was already in flight. This is rare, but it shows that hand-written cleanup needs care.
What we want instead
The limits point to the same fix: the object that owns the resource should define its own setup and cleanup. Callers then mark a block of code and get both automatically. Python's with statement does exactly that. It gives the same guarantee as try/finally in a form that is hard to misuse:
with open("data.txt", "w") as f:
f.write("hello")Summary of the trade-offs
| Approach | Cleanup on error | Easy to forget | Multiple resources |
|---|---|---|---|
| Plain calls | No | Yes | Flat, but unsafe |
| try/finally | Yes | Yes | Nests deeply |
| with | Yes | No | One line each |
Exercise
A colleague writes try: f = open(path); data = f.read() finally: f.close(). Name the bug that appears when path does not exist, and say how to fix it.
Show answer
If open(path) raises, f is never assigned, so f.close() in finally raises NameError and hides the real FileNotFoundError. Fix it by calling open() before the try statement, so finally only runs once the resource exists. Better, use with open(path) as f:.