On this page
  1. contextlib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Managing a Variable Number of Resources with ExitStack
  7. 2. Clean Cleanup Helpers (suppress, closing, redirect_stdout)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

contextlib

Prev: configparser | Up: stdlib_module | Next: contextvars
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — contextlib
Tags: #public #python3 #stdlib


Import

import contextlib

Overview

Utilities for writing and composing context managers (with / async with blocks) cleanly—turning setup/teardown generators into @contextmanagers, managing a dynamic number of resources with ExitStack, suppressing expected exceptions with suppress, and ensuring .close() runs with closing.

Quick Start

from contextlib import contextmanager

@contextmanager
def managed_tag(name: str):
    out = [f"<{name}>"]
    try:
        yield out
    finally:
        out.append(f"</{name}>")

with managed_tag("section") as buf:
    buf.append("body")
assert "".join(buf) == "<section>body</section>"

Implementation Walkthrough

1. Managing a Variable Number of Resources with ExitStack

When you don't know how many files or connections you'll open until runtime, ExitStack unwinds them in strict LIFO order even if one fails partway through:

from contextlib import ExitStack
from pathlib import Path

def read_all(paths: list[Path]) -> list[str]:
    with ExitStack() as stack:
        handles = [stack.enter_context(p.open("r", encoding="utf-8")) for p in paths]
        return [fh.read() for fh in handles]

2. Clean Cleanup Helpers (suppress, closing, redirect_stdout)

from contextlib import redirect_stdout, suppress
import io

with suppress(KeyError):
    del {"a": 1}["missing"]

captured = io.StringIO()
with redirect_stdout(captured):
    print("captured line")
assert captured.getvalue() == "captured line\n"

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes