From 20a4450bd563bf716ed1b11597aabab0d984a78b Mon Sep 17 00:00:00 2001 From: Jake Wallin Date: Tue, 20 Oct 2026 02:33:07 +0000 Subject: [PATCH] gh-131837: Clarify context variable lifetime in closures --- Doc/library/contextvars.rst | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Doc/library/contextvars.rst b/Doc/library/contextvars.rst index b0cc0be8e911bf0..4c5d97b44e48ffd 100644 --- a/Doc/library/contextvars.rst +++ b/Doc/library/contextvars.rst @@ -37,10 +37,13 @@ Context Variables :meth:`ContextVar.get` when no value for the variable is found in the current context. - **Important:** Context Variables should be created at the top module - level and never in closures. :class:`Context` objects hold strong - references to context variables which prevents context variables - from being properly garbage collected. + **Important:** Prefer creating context variables at module level rather + than in closures. A :class:`Context` holds strong references to the + variables that have values set in it. A variable created in a closure can + therefore remain alive after the closure returns, for as long as it has a + value in a reachable context. Repeatedly creating and setting new variables + in a long-lived context can accumulate variables that would otherwise be + garbage collected. :class:`!ContextVar`\s are :ref:`generic ` over the type of their contained value.