๐ช Context Managers
Context managers allow you to allocate and release resources precisely when you want to.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import time import threading from contextlib import contextmanager, asynccontextmanager, suppress # 1. Class-based context manager class DBTransaction: """Wraps DB operations in a commit/rollback context.""" def __init__(self, db_name: str): self.db_name = db_name self._queries = [] def __enter__(self): print(f"[{self.db_name}] BEGIN TRANSACTION") return self # Returned as the 'as' variable def execute(self, sql: str): self._queries.append(sql) print(f" EXEC: {sql}") def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: print(f"[{self.db_name}] COMMIT ({len(self._queries)} queries)") else: print(f"[{self.db_name}] ROLLBACK โ {exc_val}") return False # False = don't suppress exceptions with DBTransaction("pynfinity.db") as txn: txn.execute("UPDATE users SET score=95 WHERE name='santoshtvk'") txn.execute("INSERT INTO xp_log VALUES ('pebble',100)") # 2. @contextmanager โ generator-based @contextmanager def pynfinity_timer(label: str = ""): print(f"โถ Starting: {label}") start = time.perf_counter() try: yield # <-- 'with' block body runs here finally: elapsed = (time.perf_counter() - start) * 1000 print(f"โ {label} done in {elapsed:.2f}ms") with pynfinity_timer("Heavy computation"): result = sum(i**2 for i in range(500_000)) # 3. suppress โ silently ignores specific exceptions with suppress(FileNotFoundError): open("nonexistent_pynfinity_file.txt") print("suppress worked โ no crash!") # 4. Threading Lock as context manager lock = threading.Lock() counter = 0 def increment(n=10_000): global counter for _ in range(n): with lock: # Automatically acquires and releases counter += 1 threads = [threading.Thread(target=increment) for _ in range(5)] for t in threads: t.start() for t in threads: t.join() print(f"Thread-safe counter: {counter:,}") # 5. Multiple managers on one line (Python 3.10+) with ( pynfinity_timer("Double context"), suppress(ValueError), ): int("not_a_number") # Would normally crash โ suppressed!
Keep exploring and happy coding! ๐ป