Created
May 4, 2021 08:49
-
-
Save kissgyorgy/8927a1d01484f1dfbe5b5995892aeaac to your computer and use it in GitHub Desktop.
Python: Handling closing of asynchronous coroutine properly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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