Sub topic 4
Starting your program with asyncio.run
This chapter covers how a synchronous program starts the event loop and hands it a first coroutine. It assumes you can write a coroutine with async def and await, and that you know what an event loop is.
The problem: calling a coroutine does not run it
Calling an async def function does not execute its body. It returns a coroutine object, which is a paused computation that needs an event loop to drive it.
import asyncio
async def greet():
return "hello"
coro = greet()
print(type(coro))
coro.close()This prints <class 'coroutine'>. The body never ran. Without the coro.close() call, Python would warn that the coroutine was never awaited.
You can only use await inside another coroutine. Something at the top of your program must therefore be synchronous code that starts the loop. That is the job of asyncio.run.
What asyncio.run does
asyncio.run(coro) is the standard entry point. In order, it:
- Creates a new event loop.
- Runs the coroutine you passed until it finishes.
- Cancels any tasks still pending and waits for them to finish.
- Shuts down async generators and the default thread pool executor.
- Closes the loop and returns the coroutine's result.
If the coroutine raises an exception, asyncio.run re-raises it in your synchronous code.
import asyncio
async def main():
await asyncio.sleep(0.1)
return 42
result = asyncio.run(main())
print(result)This prints 42. The returned value comes out of asyncio.run like an ordinary function return value.
The diagram below shows the lifecycle.
The conventional main function
Most programs define one async def main() and pass it to asyncio.run under a main guard.
import asyncio
async def main():
print("start")
await asyncio.sleep(0.1)
print("end")
if __name__ == "__main__":
asyncio.run(main())Note that you pass main(), the coroutine object, not main, the function. Passing the function raises a ValueError.
Common errors
- Calling asyncio.run inside a running loop.
asyncio.runraisesRuntimeError: asyncio.run() cannot be called from a running event loop. Inside async code, useawaitorasyncio.create_taskinstead. - Calling it more than once is allowed, but each call gets a fresh loop. Tasks, queues, and locks created in one call should not be reused in another.
- Forgetting the call. Writing
main()withoutasyncio.runonly creates a coroutine object, and nothing runs. - Jupyter and IPython. These environments already run a loop, so use top-level
awaitthere instead ofasyncio.run.
Seeing the cleanup behavior
import asyncio
async def background():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("background cancelled")
raise
async def main():
asyncio.create_task(background())
await asyncio.sleep(0.1)
print("main done")
asyncio.run(main())The output is main done followed by background cancelled. asyncio.run cancelled the leftover task as part of shutdown.
Exercise
What happens if you write asyncio.run(main) instead of asyncio.run(main()), where main is an async def function?
Show answer
It raises a ValueError, because asyncio.run needs a coroutine object and main is the function itself. Calling main() produces the coroutine object that asyncio.run can run.
Exercise
A task is still sleeping when main returns. What does asyncio.run do with it?
Show answer
It cancels the task, so a CancelledError is raised inside it. It then waits for the task to finish before closing the loop.