]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.14] gh-142119: Clarify context manager protocol documentation on `ContextVar.set...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Mon, 26 Jan 2026 15:56:19 +0000 (16:56 +0100)
committerGitHub <noreply@github.com>
Mon, 26 Jan 2026 15:56:19 +0000 (15:56 +0000)
(cherry picked from commit 04d497c284ac933488cc747b3f7082beab300848)

Co-authored-by: Bartosz Sławecki <bartosz@ilikepython.com>
Doc/library/contextvars.rst

index 57580ce026e96ac2366dd5f3ed19323cac155493..043a8d9d9205bdf5a380c5388e4a7c66dbc34fbe 100644 (file)
@@ -77,6 +77,32 @@ Context Variables
       to restore the variable to its previous value via the
       :meth:`ContextVar.reset` method.
 
+      For convenience, the token object can be used as a context manager
+      to avoid calling :meth:`ContextVar.reset` manually::
+
+          var = ContextVar('var', default='default value')
+
+          with var.set('new value'):
+              assert var.get() == 'new value'
+
+          assert var.get() == 'default value'
+
+      It is a shorthand for::
+
+          var = ContextVar('var', default='default value')
+
+          token = var.set('new value')
+          try:
+              assert var.get() == 'new value'
+          finally:
+              var.reset(token)
+
+          assert var.get() == 'default value'
+
+      .. versionadded:: 3.14
+
+         Added support for using tokens as context managers.
+
    .. method:: reset(token)
 
       Reset the context variable to the value it had before the
@@ -101,16 +127,8 @@ Context Variables
    the value of the variable to what it was before the corresponding
    *set*.
 
-   The token supports :ref:`context manager protocol <context-managers>`
-   to restore the corresponding context variable value at the exit from
-   :keyword:`with` block::
-
-       var = ContextVar('var', default='default value')
-
-       with var.set('new value'):
-           assert var.get() == 'new value'
-
-       assert var.get() == 'default value'
+   Tokens support the :ref:`context manager protocol <context-managers>`
+   to automatically reset context variables. See :meth:`ContextVar.set`.
 
    .. versionadded:: 3.14