Regarding the following SO answer . I've made some changes in order to understand the difference between do use Contextvars and don't.
I expect at some point the variable myid
gets corrupted but changing the range to a higher number seems doesn't affect at all.
import asyncio
import contextvars
# declare context var
request_id = contextvars.ContextVar('Id of request.')
async def some_inner_coroutine(myid):
# get value
print('Processed inner coroutine of myid : {}'.format(myid))
print('Processed inner coroutine of request: {}'.format(request_id.get()))
if myid != request_id.get():
print("ERROR")
async def some_outer_coroutine(req_id):
# set value
request_id.set(req_id)
await some_inner_coroutine(req_id)
# get value
print('Processed outer coroutine of request: {}'.format(request_id.get()))
async def main():
tasks = []
for req_id in range(1, 1250):
tasks.append(asyncio.create_task(some_outer_coroutine(req_id)))
await asyncio.gather(*tasks)
if __name__ == '__main__':
asyncio.run(main())
Results
Processed inner coroutine of myid : 1
Processed inner coroutine of request: 1
Processed outer coroutine of request: 1
Processed inner coroutine of myid : 2
Processed inner coroutine of request: 2
Processed outer coroutine of request: 2
Processed inner coroutine of myid : 3
Processed inner coroutine of request: 3
Processed outer coroutine of request: 3
Processed inner coroutine of myid : 4
Processed inner coroutine of request: 4
Processed outer coroutine of request: 4
...
...
Processed inner coroutine of myid : 1244
Processed inner coroutine of request: 1244
Processed outer coroutine of request: 1244
Processed inner coroutine of myid : 1245
Processed inner coroutine of request: 1245
Processed outer coroutine of request: 1245
Processed inner coroutine of myid : 1246
Processed inner coroutine of request: 1246
Processed outer coroutine of request: 1246
Processed inner coroutine of myid : 1247
Processed inner coroutine of request: 1247
Processed outer coroutine of request: 1247
Processed inner coroutine of myid : 1248
Processed inner coroutine of request: 1248
Processed outer coroutine of request: 1248
Processed inner coroutine of myid : 1249
Processed inner coroutine of request: 1249
Processed outer coroutine of request: 1249
What should I change to see an unexpected behaviour of the variable myid
?