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.
# 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))with when opening files. Doing f = open('file.txt') without calling f.close() later keeps the file descriptor open in the OS, which can lock the file (especially on Windows) and cause memory leaks.__exit__. If the __exit__ method returns True, it explicitly tells Python to suppress any exceptions that occurred inside the block, which can hide critical bugs.Which two dunder methods must a class implement to qualify as a Context Manager?
__enter__ (which runs setup logic and returns the resource) and __exit__ (which handles teardown logic and exception routing).
Acquiring and safely releasing a threading lock to prevent Race Conditions.
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...")Test your understanding of Context Managers (with) with these quick questions.
Question 1
What happens if a ZeroDivisionError occurs inside a `with open(...)` block?
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.
# 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))with when opening files. Doing f = open('file.txt') without calling f.close() later keeps the file descriptor open in the OS, which can lock the file (especially on Windows) and cause memory leaks.__exit__. If the __exit__ method returns True, it explicitly tells Python to suppress any exceptions that occurred inside the block, which can hide critical bugs.Which two dunder methods must a class implement to qualify as a Context Manager?
__enter__ (which runs setup logic and returns the resource) and __exit__ (which handles teardown logic and exception routing).
Acquiring and safely releasing a threading lock to prevent Race Conditions.
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...")Test your understanding of Context Managers (with) with these quick questions.
Question 1
What happens if a ZeroDivisionError occurs inside a `with open(...)` block?