Topic 52 of 58
Context Managers (with)
Overview
The with statement simplifies resource management (like opening files, establishing database connections, or acquiring thread locks). Resources require explicit setup (allocation) and explicit teardown (releasing/closing). A Context Manager guarantees that the teardown phase occurs immediately when the block exits—even if a fatal exception occurs inside the block. This prevents catastrophic resource leaks.
Syntax
python
# The classic file reading example
# The file is safely and automatically closed when the block finishes
with open("data.txt", "r") as file:
content = file.read()
print(content)
# --- Creating a Custom Context Manager ---
class CodeTimer:
def __enter__(self):
import time
self.start = time.time()
return self # This value binds to the 'as' variable
def __exit__(self, exc_type, exc_value, traceback):
import time
print(f"Execution took: {time.time() - self.start:.4f}s")
# Returning True here would suppress any exceptions!
with CodeTimer():
sum(i**2 for i in range(1_000_000))Common Pitfalls
- Forgetting to use
withwhen opening files. Doingf = open('file.txt')without callingf.close()later keeps the file descriptor open in the OS, which can lock the file (especially on Windows) and cause memory leaks. - Misunderstanding
__exit__. If the__exit__method returnsTrue, it explicitly tells Python to suppress any exceptions that occurred inside the block, which can hide critical bugs.
Interview Questions
Q:
Which two dunder methods must a class implement to qualify as a Context Manager?
A:
__enter__ (which runs setup logic and returns the resource) and __exit__ (which handles teardown logic and exception routing).
Real-World Example
Acquiring and safely releasing a threading lock to prevent Race Conditions.
example
python
import threading
bank_lock = threading.Lock()
def process_transaction():
# Automatically acquires the lock, executes the critical section,
# and guarantees release even if the transaction crashes.
with bank_lock:
print("Executing highly sensitive database write...")Check Your Knowledge
Test your understanding of Context Managers (with) with these quick questions.