contextlib.contextmanager
Prev: contextlib.ContextDecorator | Up: contextlib | Next: contextlib.ExitStack
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.asynccontextmanager
Ref: docs.python.org — contextlib.contextmanager
Tags: #public #python3 #stdlib #contextlib
Import
import contextlib
from contextlib import contextmanager
Signature & Overview
contextlib.contextmanager(func)
@contextmanager decorator.
Usage
from contextlib import contextmanager
@contextmanager
def bracket(log: list[str]):
log.append("start")
try:
yield "ready"
finally:
log.append("end")
events: list[str] = []
with bracket(events) as status:
events.append(status)
assert events == ["start", "ready", "end"]
Gotchas
- Always use
try ... finally:aroundyield: Withoutfinally:, an exception inside thewithblock skips your cleanup code. - Single-use per call: Call the decorated function fresh for each
withstatement; reusing the same context manager object raisesRuntimeError.
REPL Inspect
from contextlib import contextmanager
help(contextmanager)
Linked from
Related notes
- tuts/python3/stdlib_module/contextlib/ContextDecorator Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/ExitStack Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/aclosing Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/asynccontextmanager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AsyncExitStack shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/chdir shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/closing shared tags: #contextlib, #stdlib