Event Loop and asyncio.run
What is the event loop?
Section titled “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
Section titled “asyncio.run”asyncio.run(coro):
- creates an event loop
- runs the coroutine until complete
- closes the loop
import asyncio
async def main():
await asyncio.sleep(0.1)
return 123
print(asyncio.run(main()))Running multiple coroutines
Section titled “Running multiple coroutines”To run multiple coroutines concurrently, you’ll use:
- tasks
- gather
(covered in next pages)
Common mistake in notebooks
Section titled “Common mistake in notebooks”Some notebook environments already have an event loop running.
If asyncio.run fails there, use notebook-safe patterns.
In normal Python scripts, prefer asyncio.run.
Visualize it
Section titled “Visualize it”asyncio.run starts the event loop. It runs one coroutine until that coroutine hits an
await, at which point the coroutine suspends and hands control back to the loop, which
picks the next ready task. Nothing runs in parallel — the loop just never sits idle waiting:
flowchart LR A["asyncio.run(main)"] --> B["Event loop"] B --> C["Run a coroutine"] C -->|hits await| D["Suspend & save state"] D --> B C -->|returns| E["Task done"]
Here the loop juggles three coroutines: one runs, hits await, yields, and the loop moves
on to the next:
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – asyncio.run() Entry Point
Section titled “Exercise 1 – asyncio.run() Entry Point”Exercise 2 – Get the Running Loop
Section titled “Exercise 2 – Get the Running Loop”Exercise 3 – Schedule and Await
Section titled “Exercise 3 – Schedule and Await”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading