Created
August 4, 2018 04:54
-
-
Save txomon/b195e02bd80826be4f64c78965dea6a6 to your computer and use it in GitHub Desktop.
Python 3.7 ContextVar example in asyncio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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