Last active
May 1, 2024 02:45
-
-
Save thegamecracks/e14904a2ffe346a4f74c827d7492cc38 to your computer and use it in GitHub Desktop.
Side effects of improperly closing an asyncio event loop
This file contains 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
import asyncio | |
USE_ASYNCIO_RUN = False | |
class ImaginaryResource: | |
def __enter__(self): | |
print("1. Opening resource") | |
return self | |
def __exit__(self, exc_type, exc_val, tb): | |
print("6. Closing resource") | |
async def function(): | |
with ImaginaryResource() as resource: | |
try: | |
print("2. Working with resource") | |
await asyncio.sleep(5) | |
finally: | |
print("5. Running finally clause") | |
async def main(loop=None): | |
task = asyncio.create_task(function()) | |
await asyncio.sleep(0.5) | |
print("3. Cancelling task") | |
task.cancel() | |
if loop is not None: | |
print("4a. Stopping loop!!!") | |
loop.stop() | |
# If we yield back to event loop now, main() *will* not finish | |
await asyncio.sleep(0) | |
print("4b. Exiting main()") | |
if USE_ASYNCIO_RUN: | |
asyncio.run(main()) | |
else: | |
loop = asyncio.new_event_loop() | |
loop.run_until_complete(main(loop)) |
This file contains 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
# Using asyncio.run() | |
1. Opening resource | |
2. Working with resource | |
3. Cancelling task | |
4. Exiting main() | |
5. Running finally clause | |
6. Closing resource | |
# Using loop.stop() | |
1. Opening resource | |
2. Working with resource | |
3. Cancelling task | |
4a. Stopping loop!!! | |
Traceback (most recent call last): | |
File "main.py", line 67, in <module> | |
loop.run_until_complete(main(loop)) | |
File "asyncio\base_events.py", line 651, in run_until_complete | |
raise RuntimeError('Event loop stopped before Future completed.') | |
RuntimeError: Event loop stopped before Future completed. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment