@@ -77,6 +77,32 @@ Context Variables
7777 to restore the variable to its previous value via the
7878 :meth: `ContextVar.reset ` method.
7979
80+ For convenience, the token object can be used as a context manager
81+ to avoid calling :meth: `ContextVar.reset ` manually::
82+
83+ var = ContextVar('var', default='default value')
84+
85+ with var.set('new value'):
86+ assert var.get() == 'new value'
87+
88+ assert var.get() == 'default value'
89+
90+ It is a shorthand for::
91+
92+ var = ContextVar('var', default='default value')
93+
94+ token = var.set('new value')
95+ try:
96+ assert var.get() == 'new value'
97+ finally:
98+ var.reset(token)
99+
100+ assert var.get() == 'default value'
101+
102+ .. versionadded :: 3.14
103+
104+ Added support for using tokens as context managers.
105+
80106 .. method :: reset(token)
81107
82108 Reset the context variable to the value it had before the
@@ -101,16 +127,8 @@ Context Variables
101127 the value of the variable to what it was before the corresponding
102128 *set *.
103129
104- The token supports :ref: `context manager protocol <context-managers >`
105- to restore the corresponding context variable value at the exit from
106- :keyword: `with ` block::
107-
108- var = ContextVar('var', default='default value')
109-
110- with var.set('new value'):
111- assert var.get() == 'new value'
112-
113- assert var.get() == 'default value'
130+ Tokens support the :ref: `context manager protocol <context-managers >`
131+ to automatically reset context variables. See :meth: `ContextVar.set `.
114132
115133 .. versionadded :: 3.14
116134
0 commit comments