Skip to content

Instantly share code, notes, and snippets.

@thehesiod
Created August 1, 2018 21:21
Show Gist options
  • Save thehesiod/c2189c41dabdde133a980c62cb33da40 to your computer and use it in GitHub Desktop.
Save thehesiod/c2189c41dabdde133a980c62cb33da40 to your computer and use it in GitHub Desktop.
asyncio generator issue
import asyncio
async def generator_fn():
print(f" enter generator {id(asyncio.Task.current_task())}")
try:
while True:
yield
except:
print(f" except generator {id(asyncio.Task.current_task())}")
raise
finally:
print(f" finally generator {id(asyncio.Task.current_task())}")
async def caller():
print(f" enter caller {id(asyncio.Task.current_task())}")
try:
async for _ in generator_fn():
break
finally:
print(f" finally caller {id(asyncio.Task.current_task())}")
async def main():
print(f"enter main {id(asyncio.Task.current_task())}")
try:
await asyncio.ensure_future(caller())
finally:
print(f"exit main {id(asyncio.Task.current_task())}")
asyncio.get_event_loop().run_until_complete(main())
@thehesiod
Copy link
Author

This generates output like the following:

  enter caller 4484635776
    enter generator 4484635776
  finally caller 4484635776
    except generator 4484635912
    finally generator 4484635912
exit main 4484635640

notice how the generator except/finally don't have the same task as when it was entered, and further that it's a completely different task that I did not create.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment