PYTHON Contents

contextlib (contextmanager, ExitStack)

Use contextlib tools to create safe context managers, manage multiple resources, and guarantee cleanup under failures.

On this page

contextlib is Reliability Tooling

contextlib helps you build predictable cleanup paths. This is critical for files, locks, and resource stacks.

@contextmanager

from contextlib import contextmanager

@contextmanager
def managed_resource(open_fn, close_fn):
    r = open_fn()
    try:
        yield r
    finally:
        close_fn(r)

ExitStack for Many Resources

from contextlib import ExitStack

with ExitStack() as stack:
    f1 = stack.enter_context(open("a.txt", "r", encoding="utf-8"))
    f2 = stack.enter_context(open("b.txt", "r", encoding="utf-8"))
    data = f1.read() + f2.read()

Operational Checklist

  • Use ExitStack when number of resources is dynamic.
  • Cleanup always happens in finally paths.
  • Keep context managers small and focused.

Failure Modes

  • Leaked handles: missing cleanup under exceptions.
  • Complex nesting: deeply nested with blocks reduce readability.