contextlib.contextmanager()
contextlib.contextmanager() is a Python function in the Contextlib Module category. A decorator that creates a context manager from a generator function. The syntax is contextlib.contextmanager(func). Returns: Context manager. A typical example: from contextlib import contextmanager
@contextmanager
def temporary_file(name):
f = open(name, "w")
try:
yield f
finally:
f.close()
with temporary_file("test.txt") as f:
f.write("Hello"). A close sibling is contextlib.suppress(), which a context manager that suppresses specified exceptions. A close sibling is contextlib.redirect_stdout(), which redirects sys.stdout to a file or StringIO. A close sibling is contextlib.redirect_stderr(), which redirects sys.stderr to a file or StringIO. A close sibling is contextlib.closing(), which a context manager that calls thing.close() on exit. More about this category: Context manager utilities — contextmanager, suppress, ExitStack. Related Contextlib Module entries: contextlib.suppress(), contextlib.redirect_stdout(), contextlib.redirect_stderr(), contextlib.closing(), contextlib.nullcontext(), contextlib.ExitStack(). This page is part of the free Python Reference documentation covering 978+ functions, methods, and modules with examples and parameter details.