Skip to content

Instantly share code, notes, and snippets.

@achimnol
Last active January 10, 2018 09:35
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 achimnol/965a6aecf7b1f96207abf11469b68965 to your computer and use it in GitHub Desktop.
Save achimnol/965a6aecf7b1f96207abf11469b68965 to your computer and use it in GitHub Desktop.
async generator closing
import asyncio
import pytest
@pytest.mark.asyncio
async def test_close_asyncgen():
loop = asyncio.get_event_loop()
async def mygen():
print('mygen: 0-begin')
await asyncio.sleep(0.4)
print('mygen: 1')
yield 1
print('mygen: 2')
await asyncio.sleep(0.4)
print('mygen: 3')
yield 2
print('mygen: 4')
await asyncio.sleep(0.4)
print('mygen: 5-end')
g = mygen()
async def intr():
nonlocal g
await asyncio.sleep(0.6)
print('intr: aclosing')
await g.aclose() # expected: raise an error since generator is running
print('intr: aclosed')
t = loop.create_task(intr())
print('test: begin of async-for')
async for v in g:
print('test: generated', v)
print('test: end of async-for') # not reached???
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment