Skip to content

Commit 20a4450

Browse files
committed
gh-131837: Clarify context variable lifetime in closures
1 parent 0fba211 commit 20a4450

1 file changed

Lines changed: 7 additions & 4 deletions

File tree

‎Doc/library/contextvars.rst‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,13 @@ Context Variables
3737
:meth:`ContextVar.get` when no value for the variable is found
3838
in the current context.
3939

40-
**Important:** Context Variables should be created at the top module
41-
level and never in closures. :class:`Context` objects hold strong
42-
references to context variables which prevents context variables
43-
from being properly garbage collected.
40+
**Important:** Prefer creating context variables at module level rather
41+
than in closures. A :class:`Context` holds strong references to the
42+
variables that have values set in it. A variable created in a closure can
43+
therefore remain alive after the closure returns, for as long as it has a
44+
value in a reachable context. Repeatedly creating and setting new variables
45+
in a long-lived context can accumulate variables that would otherwise be
46+
garbage collected.
4447

4548
:class:`!ContextVar`\s are :ref:`generic <generics>` over the type of
4649
their contained value.

0 commit comments

Comments
 (0)