Context Managers in Python
Context managers allow you to properly manage resources such as files, locks, and database connections. They ensure setup and cleanup happen automatically.
Why Context Managers?
Resources must be released after use. Forgetting to close them can cause memory leaks or bugs.
💡 Context managers guarantee cleanup even if an error occurs.
Without a Context Manager
file = open("data.txt", "r")
content = file.read()
file.close()
Using with Statement
The with keyword automatically handles resource cleanup.
with open("data.txt", "r") as file:
content = file.read()
How Context Managers Work
A context manager implements two special methods:
__enter__()→ setup__exit__()→ cleanup
Creating a Custom Context Manager (Class)
class FileManager:
def __enter__(self):
print("Opening file")
self.file = open("data.txt", "w")
return self.file
def __exit__(self, exc_type, exc_value, traceback):
print("Closing file")
self.file.close()
return False
with FileManager() as f:
f.write("Hello Context Manager")
Context Managers Using contextlib
Python provides contextlib to simplify context manager creation.
from contextlib import contextmanager
@contextmanager
def open_file(name):
file = open(name, "w")
try:
yield file
finally:
file.close()
with open_file("data.txt") as f:
f.write("Using contextlib")
Handling Exceptions in Context Managers
The __exit__ method receives exception details.
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
print("An error occurred")
return False
📝 Practice:
Create a context manager that measures execution time.
Create a context manager that measures execution time.