all Python 3contextlibterm
contextlib
module
Utilities for context managers and the with statement: contextmanager, suppress, ExitStack.
Syntax
import contextlib
It spares you from writing a class with __enter__ and __exit__: the @contextmanager decorator turns a generator with a single yield into a context manager. It also has ready-made suppress for ignoring an exception, redirect_stdout, and ExitStack for an unknown number of resources. A common mistake is not wrapping yield in try/finally: then cleanup is skipped if an exception occurs inside with.
Examples
from contextlib import contextmanager, suppress
@contextmanager
def tag(name):
print(f'<{name}>')
try: yield
finally: print(f'</{name}>')
with tag('b'): print('текст') # → <b> / текст / </b>
with suppress(KeyError): {}['нет']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy