Context Managers and Resource Cleanup
The with Statement and Resource Lifetimes
BOTIE
PEP 343, created in 2005 for Python 2.5, introduced the with statement to factor out common try/finally patterns. A context manager supplies the entry and exit behavior, while the body still contains the work being performed. The resource-lifetime rules become visible at the place where the resource is used.
The Read Failed. Is the File Still Open?
A program opens a file of readings, starts converting its lines, and encounters invalid text. Control leaves the calculation before reaching a close call written at the bottom. The read failed, and the resource can remain open.
The cleanup requirement exists whether the calculation succeeds or raises an exception. We will make that lifetime visible with an in-memory text buffer, then use the same structure that files and many connection libraries support.
This local buffer model carries an error outcome to the closing piece. Python challenges exercise actual exceptions and with statements. No file is opened by this workshop.
Step 1 of 1
A Read Outcome Still Needs Cleanup
The resource is an in-memory teaching buffer, so the lifetime can be inspected without reading a real file.
| Path | Event order | Final resource state |
|---|---|---|
| All fields parse | Open, read, close | Closed; parsed values remain available |
| A field is invalid | Open, attempted read, close | Closed; the failure remains visible |
| Cleanup is omitted | Open, attempted read | Still open under this local model |
All fields parse
- Event order
- Open, read, close
- Final resource state
- Closed; parsed values remain available
A field is invalid
- Event order
- Open, attempted read, close
- Final resource state
- Closed; the failure remains visible
Cleanup is omitted
- Event order
- Open, attempted read
- Final resource state
- Still open under this local model
Give a Resource a Lifetime
Reading and closing are separate responsibilities. An invalid line prevents a total, but it does not remove the obligation to close the buffer.
Close the Buffer Even When a Line Is Bad
The text contains 4, a blank line, 7 and 3. Reading its whole-number lines gives a total of 14. The buffer must close afterward, including when a later example contains unreadable text.
BOTIE
The read outcome and the resource’s closed state
- total
- 14
- closed
- true
Follow the operations
1. Buffer contents
4 7 3
2. Open the text buffer
- lines
- 0"4"
- 1""
- 2"7"
- 3"3"
- 4""
- values
[]
- closed
- false
- error
- null
3. Read the number lines
- lines
- 0"4"
- 1""
- 2"7"
- 3"3"
- 4""
- values
- 04
- 17
- 23
- closed
- false
- error
- null
4. Close the buffer
- total
- 14
- closed
- true
5. Result
- total
- 14
- closed
- true
This local buffer model carries an error outcome to the closing piece. Python challenges exercise actual exceptions and with statements. No file is opened by this workshop.
1. Give a Resource a Lifetime
A resource is something a program acquires and must later release or finish using. An open file, a database connection, and a lock have different operations, but each has a lifetime that code needs to manage.
The object that represents a resource may remain bound to a variable after it has been closed. Keeping the name does not reopen it or make later reads valid. That is why lifetime is a separate question from whether a variable exists.
StringIO gives us a file-like text buffer in memory. Construct it from text, iterate over its lines, and inspect its closed attribute. It lets us practice acquisition and cleanup without depending on a local path or changing files on the reader’s computer.
The important observation is whether the resource was released, including on the path where the work could not finish.
2. Use with to Bound the Work
The expression after with produces a context manager. Python calls its entry behavior, runs the indented body, and calls its exit behavior as control leaves the body. For this text buffer, the exit behavior closes it.
The optional as name receives whatever the entry behavior returns. With StringIO, that is the stream itself. Other context managers can return a different value or no useful value. Do not assume the variable after as is always the manager object.
The print inside this program shows that the stream is open while the body uses it. The print after the block shows that its lifetime has ended even though the variable name still exists.
The indentation marks the region allowed to use the open stream.
Inspect the Buffer Inside and After with
The line conversions use a real in-memory Python stream.
from io import StringIO
stream = StringIO('2\n5\n')
with stream as opened:
values = [int(line) for line in opened]
print(values)
print(opened.closed)
print(stream.closed)[2, 5]
False
TrueThe values were obtained while the buffer was open. After the block, the same stream object is closed.
Check yourself
Questions on Parts 1 and 2
Question 1 of 2
What does the remaining variable establish?
Question data
A StringIO buffer is opened, used inside with, and the with block completes normally. A variable still refers to the buffer afterward.3. Let Cleanup Run on Failure
The body can raise an exception. When it does, the manager still gets its exit opportunity. A standard file-like manager closes the file and allows the processing exception to continue outward.
The caller can then decide whether to handle that error. In the example, the conversion of bad raises ValueError. The outer handler reports the failure, and the closed attribute confirms cleanup occurred.
The with statement itself does not guarantee success or require every manager to re-raise every error. A context manager can deliberately suppress an exception. We are using managers whose intended policy is cleanup without suppressing a processing failure.
Closing the stream and reporting the failed conversion are compatible outcomes.
A Bad Field Does Not Skip Closing
The failing conversion is inside with, and the expected recovery is outside it.
from io import StringIO
stream = StringIO('2\nbad\n')
try:
with stream:
values = [int(line) for line in stream]
except ValueError:
print('conversion failed')
print(stream.closed)conversion failed
TrueThe read did not succeed, but the resource was still released.
4. Understand Entry and Exit before Writing a Manager
The context-manager protocol consists of entry and exit methods named __enter__ and __exit__. A class can implement those methods directly. That can be useful when a resource object already owns other state and behavior.
For a small acquisition/cleanup pair, contextlib.contextmanager provides a generator-based interface. The @contextmanager decorator adapts the function into a manager. Code before yield handles entry. The single yielded value is made available to as. When the body finishes or fails, execution resumes around that yield.
Put required cleanup in finally around the yield. The generator must yield exactly once for a normal entry. If it catches a body exception only to log or inspect it, it must re-raise rather than accidentally tell the with statement that the failure was handled.
A recorded stage makes that entry/body/exit order visible before we manage a real buffer.
Follow a Generator Manager through Both Paths
This manager records a lifetime; it does not open an external resource.
from contextlib import contextmanager
@contextmanager
def tracked_stage(events):
events.append('enter')
try:
yield
finally:
events.append('exit')
events = []
with tracked_stage(events):
events.append('work')
print(events)
try:
with tracked_stage(events):
events.append('failing work')
raise ValueError('Cannot finish this stage')
except ValueError:
pass
print(events)['enter', 'work', 'exit']
['enter', 'work', 'exit', 'enter', 'failing work', 'exit']The second body fails, and its exit event is still recorded. The error is caught by the outer caller.
5. Say Who Owns Closing
An API accepting an already open stream must say whether it borrows the stream or takes responsibility for closing it. Both policies can be useful. A borrower leaves the stream open for its caller; an owner ends its lifetime when the operation finishes.
The first exercise explicitly transfers closing responsibility to read_total. Its tests therefore inspect the supplied stream after success and failure. A library function with a different ownership contract would need different behavior and different tests.
Avoid returning a stream from inside a with block as though it were still ready to read. The block exits before the caller gets the result, so a manager that closes that stream will already have closed it. Return the data you meant to read, or design a longer-lived owner deliberately.
A clear lifetime policy prevents one caller from closing a resource that another still expects to use.
6. Do Not Infer Other Guarantees from with
The with syntax does not by itself make a file update atomic, make a database transaction commit, or grant permission to an external service. The actual manager defines its entry and exit actions. A file manager, transaction manager and lock manager therefore have different contracts.
A cleanup routine can also fail. A new cleanup exception can complicate the original failure, which is one reason exception chaining matters. Keep cleanup small and use the resource library’s documented manager when it already provides one.
In a browser, our exercises use StringIO rather than a local file. The same control-flow ideas apply, but no real filesystem permissions, durability or database transaction behavior are being tested.
The syntax makes a lifetime boundary visible. Read the manager’s contract to know what happens at that boundary.
7. Test the Body That Does Not Finish
A success-only test can miss the exact cleanup bug this lesson began with. Raise an exception deliberately inside the managed body, catch it outside, and inspect the resource and event log. The original exception must still reach that outer handler.
Also check an empty buffer and repeated uses. A new managed_buffer call should produce a fresh stream rather than reuse one that was already closed. Validate arguments before recording an acquisition event if the interface promises that invalid arguments do not start a resource lifetime.
The workshop opens an in-memory buffer, reads its number lines and closes it. A bad line changes the read result, but the closed flag must still be true. The Python exercises then verify the actual with and contextmanager behavior.
The failure path is part of the interface, not a secondary case to leave unexamined.
0Check yourself
Questions on Parts 1 to 7
Question 1 of 5
Where should mandatory release code go?
Question data
A function decorated with contextmanager acquires a resource, then yields it inside try/finally.Try it with Botie
Build with Botie
Write and run Python