Open this example in the interactive library
Source code
import asyncio
from contextvars import ContextVar
request_id = ContextVar('request_id', default='none')
async def work(value):
token = request_id.set(value)
try:
await asyncio.sleep(0)
return request_id.get()
finally:
request_id.reset(token)
async def main():
print(await asyncio.gather(work('one'), work('two')))
asyncio.run(main())Sample output
['one', 'two']
