ID EN
Contextlib

contextmanager

Python 3.11

This function is a decorator that can be used to define a factory function for with statement context managers, without needing to create a class or separate __enter__() and __exit__() methods.

Syntax

PYTHON
@contextlib.contextmanager

Examples

Example 1
PYTHON
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)
Example 2
PYTHON
>>> 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

See Also

decorator with __enter__() __exit__() generator with with try