Reputation: 21
Contextvar 'value' doest change as it goes through 'while' cycle .
'''
import contextvars
import keyboard
import asyncio
import random
value = contextvars.ContextVar('value')
value.set('-')
async def q():
while True:
await asyncio.sleep(1)
print(value.get())
async def s():
while True:
x = random.choice(list(range(10)))
value.set(x)
await asyncio.sleep(1)
async def main():
t1 = asyncio.create_task(q())
t2 = asyncio.create_task(s())
await t1
asyncio.run(main())
The output is '---' . I want to set a new value to this context var , but i cant find any similiar cases
for the first time here so i dunno if all images are shown correct and dunno gow to paste a code here so pls help
Upvotes: 2
Views: 1486
Reputation: 110311
contextvar
s are designe exactly to isolate values across different task groups. The idea is that any calls that are "awaited" from within your task t2
will see the values set in that task, and t1
and anything called from there will "see" values set in t1
.
To put it in more concrete terms, think of the common usage of async functions to handle an http request in a web framework. A framework might choose to add into contextvars details about each request, that it does not bother passing as parameters to each function (http headers, cookies, and so on). - but each function can retrieve these as "context" - and the values must be isolated from values seen in the same function, but when called to answer another request taking place in parallel.
If you want to communicate data across several tasks and syncs, either use plain global variables, or a queue - https://docs.python.org/3/library/asyncio-queue.html - if you want to pipe values that are to be consumed in other tasks/call stacks.
Upvotes: 1