contextlib.ContextDecorator
Prev: contextlib.closing | Up: contextlib | Next: contextlib.contextmanager
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.asynccontextmanager
Ref: docs.python.org — contextlib.ContextDecorator
Tags: #public #python3 #stdlib #contextlib
Import
import contextlib
from contextlib import ContextDecorator
Signature & Overview
contextlib.ContextDecorator()
A base class or mixin that enables context managers to work as decorators.
Usage
from contextlib import ContextDecorator
class Track(ContextDecorator):
events: list[str] = []
def __enter__(self):
self.events.append("enter")
return self
def __exit__(self, *exc):
self.events.append("exit")
return False
@Track()
def work() -> int:
return 42
assert work() == 42 and Track.events == ["enter", "exit"]
Gotchas
- Dual-use (
withblock OR@decorator): Inheriting fromContextDecoratorlets the same class work both ways. - Must be re-usable: Decorated functions share the same
ContextDecoratorinstance across calls, so avoid storing per-call state onselfwithout resetting it.
REPL Inspect
from contextlib import ContextDecorator
help(ContextDecorator)
Linked from
Related notes
- tuts/python3/stdlib_module/contextlib/closing Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/contextmanager Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/aclosing Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/asynccontextmanager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AsyncExitStack shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/chdir shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/ExitStack shared tags: #contextlib, #stdlib