10.3 Context Managers
Learning context managers and the "with" statement for safe management of resources like files and network connections.
Context managers are a powerful Python feature used for efficient resource management. They ensure that resources (like files, database connections, or locks in multi-threaded applications) are properly initialized and, most importantly, automatically released (cleaned up), even if an error occurs during their use. This is achieved through the `with` statement and objects that implement the "context manager protocol," namely the special methods `__enter__()` and `__exit__()`.
class MyContextManager:
def __enter__(self):
print("Entering the context (e.g., opening a resource).")
# The resource could be returned here
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# exc_type, exc_val, exc_tb will have values if an error occurred
print("Exiting the context (e.g., closing the resource).")
if exc_type:
print(f"An exception occurred: {exc_type.__name__}")
# If we return True from here, the exception is "suppressed"
return False
with MyContextManager() as manager:
print("Inside the 'with' block. The resource is now available.")
# uncomment to see exception handling:
# raise ValueError("Simulating an error")
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.