🌱 Junior Track 20 of 20

20. Context Managers

Guarantee deterministic setup and resource cleanup: master the `with` statement, `__enter__` and `__exit__` dunder methods, class-based context managers, and `contextlib.contextmanager`.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 20 — CONTEXT MANAGERS (__ENTER__, __EXIT__, CONTEXTLIB)
# ==============================================================================

from contextlib import contextmanager, suppress
import time

# 1. Class-Based Custom Context Manager
class ManagedResource:
    def __init__(self, resource_name: str):
        self.resource_name = resource_name

    def __enter__(self):
        print(f"[RESOURCE] Acquired '{self.resource_name}'")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"[RESOURCE] Released '{self.resource_name}'")
        if exc_type:
            print(f"[CLEANUP] Exception detected: {exc_val}")
        return False  # Do not suppress exceptions


# 2. Generator-Based Context Manager using contextlib.contextmanager
@contextmanager
def timer_block(label: str):
    start_time = time.perf_counter()
    try:
        yield
    finally:
        elapsed = time.perf_counter() - start_time
        print(f"[TIMER] '{label}' took {elapsed:.4f} seconds")


if __name__ == "__main__":
    with ManagedResource("Cloud Database Connection") as res:
        print("Executing queries inside protected resource context...")

    with timer_block("Data Processing Loop"):
        sum([x ** 2 for x in range(100_000)])

    # Suppressing specific exceptions cleanly
    with suppress(ZeroDivisionError):
        result = 10 / 0
    print("ZeroDivisionError cleanly suppressed!")
🌱 Junior Track 20 Master Reference

20. Context Manager Protocol & Standard Library Utilities

📊 Context Manager Protocol Features

Feature / Method Type Behavior & Description
__enter__(self) Dunder Method Initializes resource; value returned is bound to `as var`.
__exit__(self, ...) Dunder Method Guaranteed cleanup; return True to suppress exceptions.
@contextmanager Decorator Converts generator function (`yield`) into a context manager.
contextlib.suppress Utility Suppresses specified exception types safely within block.

⭐ Rate Track 20: Context Managers & with (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 19. Decorators 🌱 Junior Hub ⭐ Practice 100+ Python Questions →