Python 3.2+contextlibterm
contextlib.ContextDecorator
managers
A base class letting a context manager also be used as a function decorator.
Syntax
class C(contextlib.ContextDecorator): ...
It exists so you do not have to wrap a whole function body in with for the same manager every time — but the @cm form gives you no way to reach the value the manager yields via as, so it only fits managers used for their side effect. The default _recreate_cm() returns the very same object, so a single-use manager breaks on the second call to the decorated function unless you override it; @contextmanager already does this and rebuilds its generator per call.
Examples
import contextlib
print(hasattr(contextlib.ContextDecorator, '_recreate_cm')) # → True
print('__call__' in vars(contextlib.ContextDecorator)) # → True
print(callable(contextlib.ContextDecorator())) # → True
print(hasattr(contextlib.ContextDecorator, '__enter__'), hasattr(contextlib.ContextDecorator, '__exit__')) # → False False
gen_cm = contextlib.contextmanager(lambda: iter([None]))
print(isinstance(gen_cm(), contextlib.ContextDecorator)) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy