Skip to content

Instantly share code, notes, and snippets.

@kissgyorgy
Created May 4, 2021 08:49
Show Gist options
  • Save kissgyorgy/8927a1d01484f1dfbe5b5995892aeaac to your computer and use it in GitHub Desktop.
Save kissgyorgy/8927a1d01484f1dfbe5b5995892aeaac to your computer and use it in GitHub Desktop.
Python: Handling closing of asynchronous coroutine properly
# https://www.python.org/dev/peps/pep-0525/
import asyncio
async def generate_numbers():
i = 0
while True:
try:
yield i
except GeneratorExit:
print("Closing")
break
i += 1
print("Infinite loop finished")
async def main():
numgen = generate_numbers()
async for i in numgen:
print(i)
if i == 10:
break
await numgen.aclose()
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment