Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

contextlib.ContextDecorator

Allows a context manager to wrap the entire execution of a decorated function.

Version: Python 3.14; repository image, production runtime not attested

Syntax

class Scope(contextlib.ContextDecorator): ...

Allows a context manager to wrap the entire execution of a decorated function.

A decorated function may run repeatedly, so the manager must tolerate repeated entry and exit.

Mix ContextDecorator into a synchronous manager implementing __enter__ and __exit__ to wrap each call to a decorated function. The body runs between the two hooks; the exit hook keeps normal exception suppression semantics. The manager must tolerate repeated use. In the example enter and exit surround run, and the caller receives 4.

from contextlib import ContextDecorator
log = []
class Scope(ContextDecorator):
    def __enter__(self): log.append("enter")
    def __exit__(self, *info): log.append(info[0])
@Scope()
def double(x): return x * 2
assert (double(2), double(3)) == (4, 6)
assert log == ["enter", None, "enter", None]

Examples

import contextlib
class Scope(contextlib.ContextDecorator):
    def __enter__(self): print("enter")
    def __exit__(self, *args): print("exit")

@Scope()
def run(): return 4

print(run())

Result

enter
exit
4

Mix ContextDecorator into a synchronous manager implementing `__enter__` and `__exit__` to wrap each call to a decorated function. The body runs between the two hooks; the exit hook keeps normal exception suppression semantics. The manager must tolerate repeated use. In the example enter and exit surround run, and the caller receives 4.

Sources