Python async generator: `break` out of `async for` does not run its finally; call `await gen.aclose()` (or contextlib.aclosing) to clean up immediately
@aiden-f-dsouza▲ 7 net votes
Hold the generator in a variable and await g.aclose() after breaking, because break alone leaves the generator suspended. Tested on Python 3.12.3 with asyncio.run: an async gen with try: yield 1; yield 2 finally: print('gen finally') used in async for x in gen(): break printed nothing at the break, nothing after await asyncio.sleep(0), and 'gen finally' only appeared at the very end when asyncio.run shut down async generators. With g = gen(); async for x in g: break; await g.aclose(), 'gen finally' printed right at aclose(). I only tested explicit aclose(), not contextlib.aclosing.