The event loop is the core of asyncio in Python. It handles executing asynchronous code and callbacks when futures, tasks, etc complete. Getting, creating, and managing the event loop properly is key to writing efficient asyncio programs.
What is an Event Loop?
An event loop essentially runs a program's asynchronous code and callbacks. It:
The event loop allows asyncio to execute code concurrently while it waits on long running operations like network requests. This is more efficient than traditional synchronous code.
Here's a simple event loop example:
import asyncio
async def my_async_func():
print('hello from async function')
loop = asyncio.get_event_loop()
loop.run_until_complete(my_async_func())
loop.close()
This executes
Getting the Event Loop
There are a few ways to get the event loop:
loop = asyncio.get_event_loop() # new event loop
loop = asyncio.get_running_loop() # current loop
loop = asyncio.new_event_loop() # new event loop
Best practice is to keep a reference to the loop instead of calling
loop = asyncio.get_event_loop()
async def main():
print(asyncio.get_running_loop() is loop) # True
loop.run_until_complete(main())
Reusing the loop allows proper cleanup and resource management.
Running the Event Loop
Once you have a loop, you need to run it to execute coroutines and callbacks:
loop.run_until_complete(coro_or_future)
loop.run_forever()
For example:
async def main():
print('hello')
loop = asyncio.get_event_loop()
loop.run_until_complete(main()) # runs main()
loop.close() # cleanup
This runs
Cleaning Up After Using the Event Loop
It's important to properly clean up after the event loop when done:
loop.stop()
loop.close()
Failing to close event loops can lead to issues like resource warnings or pending callbacks/tasks not running.
So in summary, best practice is:
- Get an event loop
- Run coroutines/futures with
run_until_complete() orrun_forever() - Call
loop.stop() to halt loop execution - Clean up with
loop.close()
Event Loop Gotchas
There are some common event loop pitfalls:
So be mindful that the event loop runs perpetually once started via
Conclusion
The event loop is the secret sauce making asyncio concurrent and efficient. Getting, running, and closing it properly ensures programs work smoothly without issues. Following best practices around creating and reusing the event loop prevents tricky bugs. With a solid grasp of event loops, leveraging asyncio for writing asynchronous Python becomes much simpler.