๐ช Python Context Managers โ The with Statement Explained
Context managers ensure resources (files, DB connections, locks) are always properly cleaned up, even when exceptions occur.
Context managers are NOT just for files. Use them for database transactions, locking, temporary directories, and mocking in tests.
๐ป Code Example:
# 1. Built-in context manager โ file handling with open('pynfinity_log.txt', 'w') as f: f.write("Session started by santoshtvk\n") # File is automatically closed here โ no need for f.close() # 2. Multiple context managers in one line (Python 3.10+ parenthesized) with ( open('input.txt', 'r') as fin, open('output.txt', 'w') as fout, ): fout.write(fin.read()) # 3. Creating your own context manager with contextlib from contextlib import contextmanager import time @contextmanager def pynfinity_timer(label="Operation"): start = time.time() try: yield # Code inside 'with' block runs here finally: elapsed = time.time() - start print(f"[pynfinity] {label} took {elapsed:.4f}s") with pynfinity_timer("Data processing"): result = sum(range(1_000_000)) # 4. Class-based context manager class DBConnection: def __enter__(self): print("Connecting to Pynfinity DB...") return self # Returned as 'conn' in: with DBConnection() as conn def __exit__(self, exc_type, exc_val, exc_tb): print("Closing DB connection") return False # False = don't suppress exceptions with DBConnection() as conn: print("Running query...")
| Concept | Key Takeaway |
|---|---|
| __enter__ | Setup โ runs when entering 'with' block |
| __exit__ | Teardown โ always runs, even on exceptions |
| @contextmanager | Easy context manager from a generator function |
| contextlib.suppress | Context manager that silently ignores specific exceptions |
Keep exploring and happy coding! ๐