How would you write a reusable context manager decorator using contextlib.contextmanager that ALSO works when applied directly to a function, like @contextmanager-decorated functions support?
Short answer
Since @contextmanager already returns a _GeneratorContextManager instance supporting BOTH 'with cm():' usage AND direct '@cm()' decoration (via ContextDecorator), you get dual usage automatically — the decorated function's ENTIRE body runs wrapped inside the context manager's…
Advertisement
AModel answer
Since @contextmanager already returns a _GeneratorContextManager instance supporting BOTH 'with cm():' usage AND direct '@cm()' decoration (via ContextDecorator), you get dual usage automatically — the decorated function's ENTIRE body runs wrapped inside the context manager's enter/exit logic.
from contextlib import contextmanager
@contextmanager
def suppress_and_log(*exceptions):
try:
yield
except exceptions as e:
logging.warning(f"Suppressed: {e}")
@suppress_and_log(ValueError)
def risky_operation():
raise ValueError("oops")
risky_operation() # logs a warning instead of crashing, thanks to decorator usageReal-world example
Building a single reusable error-suppression or logging utility usable either as an explicit 'with' block OR as a function decorator.
Likely follow-ups
- What is the specific base class (ContextDecorator) that enables this dual with/decorator usage pattern?
Related topics