Sub topic 1
Why cleanup needs a guarantee: try/finally and its limits
Prerequisites
Assume you know Python functions, classes, exceptions, and the basic use of open() for files. You should also understand try, except, and finally.
Why cleanup needs a guarantee
Resources such as files, database connections, and locks must be released even when the work inside a block fails. A finally clause runs when control leaves the try block, whether normally or because of an exception.
# Manual cleanup
f = open("data.txt", "w")
try:
f.write("hello")
finally:
f.close()
# The with statement provides the same guarantee
with open("data.txt", "w") as f:
f.write("hello")The manual version is correct, but every caller must remember to write the finally clause. Missing it can leak a resource. The with statement moves that responsibility into a reusable object called a context manager.
The with statement and the as clause
The expression after with produces a context manager. The optional as clause stores the value returned by its setup method in a variable.
For a file, as f gives you the opened file object. When the indented block ends, Python closes the file, including when an exception leaves the block.
How with works: __enter__ and __exit__
A context manager follows a protocol: a required pair of methods with specific meanings.
__enter__()performs setup and returns the value used byas.__exit__()performs cleanup.- If the body raises an exception,
__exit__()receives its type, value, and traceback.
Conceptually, Python runs the block like this:
manager = open("data.txt", "w")
value = manager.__enter__()
try:
value.write("hello")
finally:
manager.__exit__(None, None, None)The real behavior also passes exception details to __exit__() when an error occurs. Its return value controls the error: False or None lets the exception continue, while True suppresses it.
Exercise
Why is a with statement safer than manually calling close() after a file operation?
Show answer
The context manager calls cleanup when the block exits, including when an exception interrupts the body.