pythonintermediate

Custom Context Manager with __enter__ / __exit__

Build reusable resource management with Python context managers.

python
import time
from contextlib import contextmanager

# Class-based context manager
class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.elapsed = time.perf_counter() - self.start
        print(f"Elapsed: {self.elapsed:.4f}s")
        return False  # Don't suppress exceptions

with Timer() as t:
    sum(range(1_000_000))

# Generator-based (simpler)
@contextmanager
def temp_directory():
    import tempfile, shutil
    path = tempfile.mkdtemp()
    try:
        yield path
    finally:
        shutil.rmtree(path)

with temp_directory() as tmpdir:
    print(f"Working in {tmpdir}")

Use Cases

  • Resource cleanup
  • Timing code
  • Temporary directories
  • Database connections

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.