Python Context Managers
Context managers provide a clean way to manage resources such as files, database connections, and locks. They automatically handle setup and cleanup.
Using the with Statement
The with statement automatically closes a file after the block finishes, even when an exception occurs.
with open("data.txt", "r") as file:
content = file.read()
print(content)
Create a Context Manager
A class can act as a context manager by implementing enter and exit.
class Manager:
def __enter__(self):
print("Started")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Finished")
with Manager():
print("Inside block")
enter and exit
enter runs when the with block starts. exit runs when the block ends and can be used for cleanup or exception handling.
Using contextlib
The contextlib module provides utilities for creating context managers without defining a full class.
from contextlib import contextmanager
@contextmanager
def resource():
print("Start")
try:
yield
finally:
print("Cleanup")
with resource():
print("Working")
Common Use Cases
Context managers are commonly used for files, database connections, locks, temporary resources, network connections, and transaction handling.
Why Use Context Managers?
They reduce cleanup code, make resource handling safer, and ensure cleanup happens consistently.
Summary
Python context managers use the with statement to manage resources safely. You can use built-in context managers, create classes with enter and exit, or use contextlib.