Skip to content

Commit e393c79

Browse files
committed
gh-99633: Use testcode to test contextvars.Context.run example
1 parent 713d4fe commit e393c79

File tree

1 file changed

+39
-19
lines changed

1 file changed

+39
-19
lines changed

Doc/library/contextvars.rst

Lines changed: 39 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -158,33 +158,53 @@ Manual Context Management
158158
or propagate an exception if one occurred.
159159

160160
Any changes to any context variables that *callable* makes will
161-
be contained in the context object::
161+
be contained in the context object.
162162

163-
var = ContextVar('var')
164-
var.set('spam')
163+
Example:
165164

166-
def main():
167-
# 'var' was set to 'spam' before
168-
# calling 'copy_context()' and 'ctx.run(main)', so:
169-
# var.get() == ctx[var] == 'spam'
165+
.. testcode::
170166

171-
var.set('ham')
167+
import contextvars
172168

173-
# Now, after setting 'var' to 'ham':
174-
# var.get() == ctx[var] == 'ham'
169+
var = contextvars.ContextVar('var')
170+
var.set('spam')
171+
print(var.get()) # 'spam'
175172

176-
ctx = copy_context()
173+
ctx = contextvars.copy_context()
177174

178-
# Any changes that the 'main' function makes to 'var'
179-
# will be contained in 'ctx'.
180-
ctx.run(main)
175+
def main():
176+
# 'var' was set to 'spam' before
177+
# calling 'copy_context()' and 'ctx.run(main)', so:
178+
print(var.get()) # 'spam'
179+
print(ctx[var]) # 'spam'
181180

182-
# The 'main()' function was run in the 'ctx' context,
183-
# so changes to 'var' are contained in it:
184-
# ctx[var] == 'ham'
181+
var.set('ham')
185182

186-
# However, outside of 'ctx', 'var' is still set to 'spam':
187-
# var.get() == 'spam'
183+
# Now, after setting 'var' to 'ham':
184+
print(var.get()) # 'ham'
185+
print(ctx[var]) # 'ham'
186+
187+
# Any changes that the 'main' function makes to 'var'
188+
# will be contained in 'ctx'.
189+
ctx.run(main)
190+
191+
# The 'main()' function was run in the 'ctx' context,
192+
# so changes to 'var' are contained in it:
193+
print(ctx[var]) # 'ham'
194+
195+
# However, outside of 'ctx', 'var' is still set to 'spam':
196+
print(var.get()) # 'spam'
197+
198+
.. testoutput::
199+
:hide:
200+
201+
spam
202+
spam
203+
spam
204+
ham
205+
ham
206+
ham
207+
spam
188208

189209
The method raises a :exc:`RuntimeError` when called on the same
190210
context object from more than one OS thread, or when called

0 commit comments

Comments
 (0)