Python contextlib Module
Example
Create a simple context manager:
import contextlib
@contextlib.contextmanager
def greet(name):
print("Hello, " + name)
try:
yield
finally:
print("Goodbye, " + name)
with greet("Emil"):
print("inside")
Try it Yourself »
Definition and Usage
The contextlib module utilities help you write and manipulate context managers.
Use it to create context managers from generator functions, manage multiple contexts, and suppress exceptions.
Members
| Member | Description |
|---|---|
| AbstractAsyncContextManager | Base class for async context managers. |
| AbstractContextManager | Base class for context managers. |
| aclosing() | Async context manager that calls aclose() on exit. |
| asynccontextmanager() | Decorator to define an async context manager from an async generator. |
| chdir() | Temporarily change the current working directory inside a with block. |
| closing() | Return a context manager that closes an object on exit. |
| contextmanager() | Decorator to define a context manager from a generator. |
| AsyncExitStack | Async variant of ExitStack for managing multiple async context managers. |
| ExitStack | Context manager for dynamic management of multiple context managers. |
| nullcontext() | Context manager that does no additional processing. |
| redirect_stderr() | Context manager to redirect sys.stderr. |
| redirect_stdin() | Context manager to redirect sys.stdin. |
| redirect_stdout() | Context manager to redirect sys.stdout. |
| suppress() | Context manager to suppress specified exceptions. |