28.7. contextlib — Utilities for with-statement contexts¶
New in version 2.5.
Source code: Lib/contextlib.py
This module provides utilities for common tasks involving the with
statement. For more information see also Context Manager Types and
With Statement Context Managers.
Functions provided:
-
contextlib.contextmanager(func)¶ This function is a decorator that can be used to define a factory function for
withstatement context managers, without needing to create a class or separate__enter__()and__exit__()methods.While many objects natively support use in with statements, sometimes a resource needs to be managed that isn’t a context manager in its own right, and doesn’t implement a
close()method for use withcontextlib.closingAn abstract example would be the following to ensure correct resource management:
from contextlib import contextmanager @contextmanager def managed_resource(*args, **kwds): # Code to acquire resource, e.g.: resource = acquire_resource(*args, **kwds) try: yield resource finally: # Code to release resource, e.g.: release_resource(resource) >>> with managed_resource(timeout=3600) as resource: ... # Resource is released at the end of this block, ... # even if code in the block raises an exception
The function being decorated must return a
