contextlib — context manager utilities
contextmanager, suppress, closing, ExitStack, and nullcontext, including exception suppression and stack unwinding, checked on Python 3.13.12.
模块页正文目前为英文。
contextmanager, suppress, and closing
A generator decorated with @contextmanager yields once. The example prints enter, then the yielded value, then exit in a finally block so exit still runs if the body raises.
suppress(FileNotFoundError) ignores that error and no other. The missing path is a name inside a TemporaryDirectory, not a user file. A ValueError still propagates. closing(thing) calls thing.close() when the block exits, which the example uses on a tiny resource object.
contextmanager, suppress, closing
contextlib.contextmanager(func)
contextlib.suppress(*exceptions)
contextlib.closing(thing)
Build a context manager from a generator, ignore selected exceptions, or close a resource on exit.
| Parameter | Description |
|---|
*exceptions | The exception types suppress should ignore. Other exceptions still propagate. |
thing | An object with a close() method, for closing(). |
Returns: Each helper returns a context manager. contextmanager-wrapped functions yield the value you yield from the generator.
- suppress is not a generic except Exception. Only the listed types are ignored.
import os
import tempfile
from contextlib import closing, contextmanager, suppress
@contextmanager
def mark(label):
print("enter", label)
try:
yield label
finally:
print("exit", label)
with mark("a") as value:
print("inside", value)
with tempfile.TemporaryDirectory(prefix="ctx-ref-") as folder:
with suppress(FileNotFoundError):
os.remove(os.path.join(folder, "missing.txt"))
print("after-suppress")
try:
with suppress(FileNotFoundError):
raise ValueError("nope")
except ValueError as exc:
print("not-suppressed", type(exc).__name__)
class Resource:
def __init__(self):
self.closed = False
def close(self):
self.closed = True
with closing(Resource()) as resource:
print("open", resource.closed)
print("closed", resource.closed)
Expected output
enter a
inside a
exit a
after-suppress
not-suppressed ValueError
open False
closed True
Official documentation →
ExitStack, callbacks, and nullcontext
ExitStack.enter_context(cm) enters a context manager and schedules its exit. callback(print, "callback") registers an arbitrary function. When the example raises RuntimeError, the callback runs first, then exit 2, then exit 1, and the exception still propagates.
nullcontext(enter_result) yields that value and does nothing else. pop_all() moves the current stack to a new ExitStack so the original with-block can exit without closing those resources; the example then calls leftover.close() to run them.
ExitStack, enter_context, callback, pop_all, nullcontext
contextlib.ExitStack()
ExitStack.enter_context(cm)
ExitStack.callback(callback, /, *args, **kwds)
ExitStack.pop_all()
contextlib.nullcontext(enter_result=None)
Enter a dynamic stack of context managers, register callbacks, transfer the stack, or use a no-op context.
| Parameter | Description |
|---|
cm | A context manager passed to enter_context. |
callback, *args, **kwds | A function and its arguments, run on exit in last-in, first-out order with the other callbacks and exits. |
enter_result | The value nullcontext yields. |
Returns: enter_context returns the entered context's __enter__ result. pop_all returns a new ExitStack that owns the transferred callbacks.
- The RuntimeError in the example exists only to show that cleanup still runs. It is caught in the same script.
from contextlib import ExitStack, contextmanager, nullcontext
@contextmanager
def mark(label):
print("enter", label)
try:
yield label
finally:
print("exit", label)
try:
with ExitStack() as stack:
first = stack.enter_context(mark("1"))
second = stack.enter_context(mark("2"))
stack.callback(print, "callback")
print("yielded", first, second)
raise RuntimeError("fail")
except RuntimeError:
print("caught")
with nullcontext("held") as value:
print("null", value)
with ExitStack() as stack:
stack.enter_context(mark("keep"))
leftover = stack.pop_all()
print("after-parent")
leftover.close()
print("after-close")
Expected output
enter 1
enter 2
yielded 1 2
callback
exit 2
exit 1
caught
null held
enter keep
after-parent
exit keep
after-close
Official documentation →