Skip to content

Commit 26d52a9

Browse files
committed
gh-134537: Clarify context manager reuse in ContextDecorator
1 parent 0fba211 commit 26d52a9

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

‎Doc/library/contextlib.rst‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -434,17 +434,18 @@ Functions and classes provided:
434434
The bit in the middle
435435
Finishing
436436

437-
This change is just syntactic sugar for any construct of the following form::
437+
The decorator form is::
438438

439+
@cm()
439440
def f():
440-
with cm():
441-
# Do stuff
441+
# Do stuff
442442

443-
``ContextDecorator`` lets you instead write::
443+
By default, this reuses a single context manager instance, as in::
444444

445-
@cm()
445+
context = cm()
446446
def f():
447-
# Do stuff
447+
with context:
448+
# Do stuff
448449

449450
It makes it clear that the ``cm`` applies to the whole function, rather than
450451
just a piece of it (and saving an indentation level is nice, too).
@@ -465,7 +466,12 @@ Functions and classes provided:
465466
As the decorated function must be able to be called multiple times, the
466467
underlying context manager must support use in multiple :keyword:`with`
467468
statements. If this is not the case, then the original construct with the
468-
explicit :keyword:`!with` statement inside the function should be used.
469+
explicit :keyword:`!with` statement and a new context manager inside the
470+
function should be used.
471+
472+
Recursive calls require the context manager to support nested use, and
473+
concurrent calls require it to be thread-safe. Context managers created
474+
by :deco:`contextmanager` are recreated for each call, as described above.
469475

470476
When the decorated callable is a generator function, coroutine function, or
471477
asynchronous generator function, the returned wrapper is of the same kind

0 commit comments

Comments
 (0)