Event Loop and asyncio.run
What is the event loop?
The event loop is the βengineβ that:
- runs coroutines
- pauses them at await points
- resumes them when I/O is ready
asyncio.run
asyncio.run(coro)asyncio.run(coro):
- creates an event loop
- runs the coroutine until complete
- closes the loop
asyncio_run.py
import asyncio
async def main():
await asyncio.sleep(0.1)
return 123
print(asyncio.run(main()))asyncio_run.py
import asyncio
async def main():
await asyncio.sleep(0.1)
return 123
print(asyncio.run(main()))Running multiple coroutines
To run multiple coroutines concurrently, youβll use:
- tasks
- gather
(covered in next pages)
Common mistake in notebooks
Some notebook environments already have an event loop running.
If asyncio.runasyncio.run fails there, use notebook-safe patterns.
In normal Python scripts, prefer asyncio.runasyncio.run.
π§ͺ Try It Yourself
Exercise 1 β asyncio.run() Entry Point
Exercise 2 β Get the Running Loop
Exercise 3 β Schedule and Await
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
