Skip to content

Instantly share code, notes, and snippets.

@qpwo
Created May 11, 2023 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qpwo/b2b199179909377e2772108b40f3c6ad to your computer and use it in GitHub Desktop.
Save qpwo/b2b199179909377e2772108b40f3c6ad to your computer and use it in GitHub Desktop.
python async context trace
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