Skip to content

Instantly share code, notes, and snippets.

@thegamecracks
Last active May 1, 2024 02:45
Show Gist options
  • Save thegamecracks/e14904a2ffe346a4f74c827d7492cc38 to your computer and use it in GitHub Desktop.
Save thegamecracks/e14904a2ffe346a4f74c827d7492cc38 to your computer and use it in GitHub Desktop.
Side effects of improperly closing an asyncio event loop
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))
# 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