Context Managers in Python π―π

A context manager is a Python construct that manages resource allocation and cleanup automatically. It ensures resources like files, database connections, and network sockets are properly released, even if an error occurs.
1οΈβ£ Why Use Context Managers?
β Automatic resource management (e.g., closing files, releasing locks)
β Prevents resource leaks
β Makes code cleaner and more readable
2οΈβ£ Using with Statements (Built-in Context Managers)
β
Example: File Handling (without explicit close())
with open("example.txt", "r") as file:
content = file.read()
print(content) # File closes automatically when 'with' block ends
β No need to call file.close() manually
β Ensures the file is closed even if an exception occurs
3οΈβ£ Creating a Custom Context Manager
You can create a custom context manager using a class with __enter__() and __exit__() methods.
β
Example: A Simple Timer Context Manager
import time
class Timer:
def __enter__(self):
self.start_time = time.time() # Start time
return self # Allows using 'as' in 'with'
def __exit__(self, exc_type, exc_value, traceback):
elapsed_time = time.time() - self.start_time
print(f"Elapsed time: {elapsed_time:.2f} seconds")
with Timer():
time.sleep(2) # Simulating a task
β Automatically measures execution time
β Handles exceptions gracefully
4οΈβ£ Using contextlib to Create Context Managers
Pythonβs contextlib module provides an easy way to create context managers using a decorator instead of a class.
β
Example: Creating a Context Manager Using @contextmanager
from contextlib import contextmanager
@contextmanager
def open_file(filename, mode):
file = open(filename, mode)
try:
yield file # Code inside 'with' block executes here
finally:
file.close() # Ensures file is closed
with open_file("example.txt", "w") as f:
f.write("Hello, Python!")
β Simpler than writing a class
β Automatically handles cleanup
5οΈβ£ Summary
Concept Description
with Statement Ensures resources are cleaned up properly
Built-in Context Managers open(), threading.Lock(), sqlite3.connect()
Custom Context Manager (Class-based) Uses __enter__() and __exit__() methods
contextlib Decorator (@contextmanager) A simpler way to create context managers
Date: 2025-03-24 00:00:00.000000