Skip to content

Instantly share code, notes, and snippets.

@kumaraditya303
Last active September 30, 2024 15:43
Show Gist options
  • Save kumaraditya303/75328749752c2fae224c46e5e2aef668 to your computer and use it in GitHub Desktop.
Save kumaraditya303/75328749752c2fae224c46e5e2aef668 to your computer and use it in GitHub Desktop.

asyncio

async generator's finalization is broken

import asyncio
work_done = False

async def cursor():
    try:
        yield 1
    finally:
        assert work_done
        print("finally cursor")

async def rows():
    global work_done
    try:
        yield 2
    finally:
        await asyncio.sleep(0.1) # <--- This line causes the issue
        work_done = True
        print("finally rows")


async def main():
    async for c in cursor():
        async for r in rows():
            break
        break

asyncio.run(main())

contextvars don't work with async generators

from contextvars import ContextVar
import asyncio

ctx = ContextVar('ctx', default=0)

async def agen():
    try:
        yield 1
    finally:
        ctx.set(1)

async def main():
    async for i in agen():
        print(ctx.get())
        break
    await asyncio.sleep(1)
    print(ctx.get())
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment