The with Statement
with ensures the resource is properly closed/released regardless of what happens.
Python
# Without context manager (bad β file may not close on error)
f = open("data.txt", "w")
f.write("Hello") # If this crashes, f.close() never runs!
f.close()
# With context manager (correct)
with open("data.txt", "w") as f:
f.write("Hello") # __exit__ calls f.close() automatically
# File is closed here β alwaysTip
Always use with for file operations. It is safer and more readable than manual open/close.
The Context Manager Protocol
Any class with __enter__ and __exit__ works as a context manager.
Python
class Timer:
import time as _time
def __enter__(self):
import time
self.start = time.time()
return self # Bound to "as" variable
def __exit__(self, exc_type, exc_val, exc_tb):
import time
elapsed = time.time() - self.start
print(f"Elapsed: {elapsed:.4f}s")
return False # Don't suppress exceptions
with Timer() as t:
total = sum(range(1_000_000))βΆ Output
Elapsed: 0.0412scontextlib.contextmanager β Generator Approach
Use @contextmanager to write context managers as generator functions β less boilerplate.
Python
from contextlib import contextmanager
@contextmanager
def managed_resource(name):
print(f"Opening {name}")
try:
yield name # Everything before yield = __enter__
finally:
print(f"Closing {name}") # Always runs = __exit__
with managed_resource("database") as r:
print(f"Working with {r}")βΆ Output
Opening database
Working with database
Closing databaseAd β 336Γ280
Multiple Context Managers
Combine multiple managers in one with statement.
Python
# Open two files simultaneously
with open("input.txt", "r") as src, open("output.txt", "w") as dst:
for line in src:
dst.write(line.upper())
# Both files auto-closed after blockcontextlib.suppress β Ignore Specific Exceptions
Cleanly suppress known safe exceptions without try/except.
Python
from contextlib import suppress
import os
# Instead of:
try:
os.remove("temp.txt")
except FileNotFoundError:
pass
# Use suppress:
with suppress(FileNotFoundError):
os.remove("temp.txt")