From 2336feac95aeb382166ee9f6f48b657c34d844e5 Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sun, 11 Jan 2026 15:56:49 +0100 Subject: [PATCH 1/2] Clarify CM protocol documentation on `ContextVar.set` and `Token` --- Doc/library/contextvars.rst | 38 +++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/Doc/library/contextvars.rst b/Doc/library/contextvars.rst index b218468a084db1..66fd9bbacdcd86 100644 --- a/Doc/library/contextvars.rst +++ b/Doc/library/contextvars.rst @@ -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 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 ` - 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 ` + to automatically reset context variables. See :meth:`ContextVar.set`. .. versionadded:: 3.14 From 4ada53979051132573225a1cf77e76e22b8923a7 Mon Sep 17 00:00:00 2001 From: johnslavik Date: Sun, 11 Jan 2026 16:53:05 +0100 Subject: [PATCH 2/2] Fix grammar error --- Doc/library/contextvars.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/contextvars.rst b/Doc/library/contextvars.rst index 66fd9bbacdcd86..60376e730cb102 100644 --- a/Doc/library/contextvars.rst +++ b/Doc/library/contextvars.rst @@ -77,7 +77,7 @@ Context Variables to restore the variable to its previous value via the :meth:`ContextVar.reset` method. - For convenience, the token object can used as a context manager + 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')