Is it nescessary to close asyncio loop upon unexpected program exit?

Viewed 355

Below you can find a snippet from my python script.

I have the following question:

Is it nescessary to close a loop explicitly like in the example below?

import asyncio

loop = asyncio.get_event_loop()
loop.run_until_complete(my_async_task())

try:
    loop.run_forever()
except KeyboardInterrupt:
    print('Stopping...')
finally:
    loop.close()
1 Answers

Since the program is exiting anyway, which will automatically release all its resources back to the OS, nothing is gained by the explicit call to loop.close() - it just makes the code a bit longer and the program slightly slower to exit.

Closing the event loop is necessary when the loop is created in (and run by) code that is invoked more than once, particularly if it's hidden behind a reusable class or function. Failing to close such a loop would leak its internal resources, such as the pipe set up for call_soon_threadsafe.

Note that explicitly catching KeyboardInterrupt is only necessarily if you want to suppress the display of the stack trace normally provided by the interpreter.

Related