@@ -158,33 +158,53 @@ Manual Context Management
158
158
or propagate an exception if one occurred.
159
159
160
160
Any changes to any context variables that *callable * makes will
161
- be contained in the context object::
161
+ be contained in the context object.
162
162
163
- var = ContextVar('var')
164
- var.set('spam')
163
+ Example:
165
164
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 ::
170
166
171
- var.set('ham')
167
+ import contextvars
172
168
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'
175
172
176
- ctx = copy_context()
173
+ ctx = contextvars. copy_context()
177
174
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'
181
180
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')
185
182
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
188
208
189
209
The method raises a :exc: `RuntimeError ` when called on the same
190
210
context object from more than one OS thread, or when called
0 commit comments