python3.7 contextvars在asyncio使用的

时间:2024-05-02 10:07:25
from contextvars import ContextVar

import asyncio
import random cv = ContextVar('cv') async def waiting_func(name):
print(f'{name} Before sleep: {cv.get()}')
await asyncio.sleep(random.random())
print(f'{name} After 1 sleep: {cv.get()}')
await asyncio.sleep(random.random())
print(f'{name} After 2 sleep: {cv.get()}') async def task(name):
await waiting_func(name) async def main():
for name in ('first', 'second', 'third'):
cvt = cv.set(name)
await task(name)
cv.reset(cvt) if __name__ == '__main__':
asyncio.run(main())