Skip to content

Instantly share code, notes, and snippets.

@txomon
Created August 4, 2018 04:54
Show Gist options
  • Save txomon/b195e02bd80826be4f64c78965dea6a6 to your computer and use it in GitHub Desktop.
Save txomon/b195e02bd80826be4f64c78965dea6a6 to your computer and use it in GitHub Desktop.
Python 3.7 ContextVar example in asyncio
from contextvars import ContextVar
import asyncio
import random
cv = ContextVar('cv')
async def waiting_func(name):
print(f'{name} Before sleep: {cv.get() == name}')
await asyncio.sleep(random.random())
print(f'{name} After 1 sleep: {cv.get() == name}')
await asyncio.sleep(random.random())
print(f'{name} After 2 sleep: {cv.get() == name}')
async def task(name):
asyncio.ensure_future(waiting_func(name))
async def main():
for name in ('first', 'second', 'third'):
cvt = cv.set(name)
await task(name)
cv.reset(cvt)
asyncio.ensure_future(main())
asyncio.get_event_loop().run_until_complete(asyncio.sleep(4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment