Created
May 11, 2023 22:55
-
-
Save qpwo/b2b199179909377e2772108b40f3c6ad to your computer and use it in GitHub Desktop.
python async context trace
This file contains 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
import asyncio | |
from contextvars import ContextVar | |
ctx = ContextVar[int]("myctx") | |
async def bar(): | |
await asyncio.sleep(1) | |
print(ctx.get(), end=" ") | |
async def main(): | |
promises = [] | |
for i in range(10): | |
promises.append(wrapper(i, bar)) | |
await asyncio.gather(*promises) | |
async def wrapper(x, f): | |
ctx.set(x) | |
await f() | |
asyncio.run(main()) | |
# Output: 0 1 2 3 4 5 6 7 8 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment