← Back to Blog
Code Snippets July 28, 2026

Reusable Context Manager with Stack Tracking (Python)

💻 Code Snippet — July 28, 2026

Reusable Context Manager with Stack Tracking (Python)

Turn any setup/teardown pair into a proper context manager with timing, stack-safe nesting, and lazy teardown.

class ManagedContext:
    def __init__(self, setup, teardown, *, stack_tracking=True, timer=False, on_exception=None):
        self.setup, self.teardown = setup, teardown
        self._tracking, self._timer, self._hook = stack_tracking, timer, on_exception
        self._depth, self._res, self._done = 0, None, False
        self._start, self._times, self._total = 0.0, [], 0.0

    def __enter__(self):
        if self._depth == 0:
            self._res = self.setup()
            self._done = True
        if self._timer: self._start = time.perf_counter()
        self._depth += 1
        return self._res

    def __exit__(self, *a):
        if self._timer and self._depth > 0:
            t = time.perf_counter() - self._start
            self._times.append(t); self._total += t
        self._depth = max(0, self._depth - 1)
        if self._depth > 0 and self._tracking: return
        sup = self._hook(a[1]) if a[1] and self._hook else None
        if self._done and self._res is not None:
            self.teardown(self._res)
            self._res, self._done = None, False
        return sup


Usage:
cm = ManagedContext(open_conn, close_conn, timer=True, stack_tracking=True)
with cm:
    with cm:  # setup runs only once!
        pass
print(f'Total: {cm._total:.4f}s')


Stack tracking → nested enters share one setup, need matching exits to teardown. .total_time for cumulative benchmarks. Zero deps, Python 3.10+.