Many operations have a beginning and an end that must be respected: opening and closing a file, locking and releasing a resource, starting and committing an operation. If you forget the end (or an error happens before reaching it), the resource is left open. The with statement and context managers exist so that the end runs always.
The problem: remembering to close
With files, the safe way is to always close with try/finally. It works, but it is long and easy to forget.
f = open("data.txt", "w", encoding="utf-8")
try:
f.write("hello\n")
f.write("world\n")
finally:
f.close()
print(f.closed) # True
The solution: with
With with the same code is shorter and the closing is automatic. The object after with is the context manager; what comes after as is the value it returns on entering.
with open("data.txt", "w", encoding="utf-8") as f:
f.write("hello\n")
f.write("world\n")
print(f.closed) # True (closed on leaving the block)
with open("data.txt", encoding="utf-8") as f:
print(f.read().splitlines()) # ['hello', 'world']
Also when there is an error
The important thing is that the closing happens even if the block fails. The error continues on its way, but the resource has already been released.
try:
with open("data.txt", encoding="utf-8") as f:
raise ValueError("something failed")
except ValueError as e:
print(e) # something failed
print(f.closed) # True
How it works inside
An object is a context manager if it has two special methods:
| Method | When it runs | What it does |
|---|---|---|
__enter__ | on entering the with block | prepares the resource and returns the value for as |
__exit__ | on leaving the block, always | releases the resource (and can decide what to do with an error) |
In the next article you will write them yourself. A first example is Section with entry and exit.
Where you will find them
- Files:
open(...)closes the file on exit. - Thread locks:
with lock:locks and releases. - Databases: a connection can commit or roll back a transaction on exit.
- Temporary directories:
tempfile.TemporaryDirectory()deletes the folder on exit. - Tests:
unittestandpytestusewithto check that an operation raises an error. - Decimal precision:
decimal.localcontext()changes the settings and restores them.
import io
with io.StringIO() as buffer:
buffer.write("in memory")
print(buffer.getvalue()) # in memory
print(buffer.closed) # True