Sub topic 4
Starting your program with asyncio.run
This chapter assumes you can write async def functions and await them, as covered in the previous chapter. It also assumes you know what a Python context manager is and how try/finally works. Here you learn how a normal, synchronous Python program hands control to the event loop, what happens at startup and shutdown, and which errors show up when you get the entry point wrong.
The bridge between sync and async
A coroutine function does not run when you call it. It returns a coroutine object, and something must drive that object. The event loop does the driving, and asyncio.run is the standard way to create a loop, drive one coroutine on it, and tear everything down.
import asyncio
async def greet(name, delay):
await asyncio.sleep(delay)
return f"Hello, {name}"
async def main():
message = await greet("Ada", 0.1)
print(message)
return len(message)
if __name__ == "__main__":
size = asyncio.run(main())
print("main returned", size)asyncio.run(main()) blocks the calling thread until main() finishes. It then returns whatever main() returned. If main() raises, the exception propagates out of asyncio.run after cleanup, so a normal try/except around the call works.
Call asyncio.run once per program, at the top level. Everything else in your program runs inside the coroutine you pass to it.
What asyncio.run does
The call performs a fixed sequence of steps. The order matters when something goes wrong during shutdown.
Three of these steps deserve attention.
- Leftover tasks are cancelled, not awaited. When
main()returns, any task you started and did not wait for receives a cancellation request.asyncio.runthen waits for those tasks to finish handling it. - Async generators are closed. Generators that were started but not exhausted get
aclose()called, so theirfinallyblocks run. - The default executor is shut down. Threads started by
asyncio.to_threadorrun_in_executorare joined. A blocked worker thread can therefore delay the exit of your program.
Seeing the cleanup
The next program starts a background task and never awaits it. Watch what happens when main() ends.
import asyncio
async def background():
try:
while True:
await asyncio.sleep(0.2)
print("background tick")
except asyncio.CancelledError:
print("background cancelled")
raise
async def main():
task = asyncio.create_task(background())
await asyncio.sleep(0.5)
print("main done")
return task
task = asyncio.run(main())
print("cancelled:", task.cancelled())The output is two ticks, then main done, then background cancelled, then cancelled: True. The task never finished its loop. asyncio.run cancelled it during shutdown and waited until it handled the cancellation.
The program keeps the task in a variable on purpose. The event loop holds only a weak reference to tasks, so a task with no other reference can be garbage collected while it is still running. Keep a reference to every task you create, or place it in a TaskGroup, which you meet later in this tutorial.
Common errors at the entry point
Calling the function but not running it
async def main():
print("hello")
main() # Nothing prints. A coroutine object is created and discarded.Python emits RuntimeWarning: coroutine 'main' was never awaited when the object is garbage collected. The fix is asyncio.run(main()). Note the parentheses: you pass the coroutine object, not the function.
Passing something that is not a coroutine
asyncio.run(main) without the call parentheses raises ValueError: a coroutine was expected. Passing a Future or a task also fails the same check, because asyncio.run needs a coroutine it can wrap in a task of its own.
Calling asyncio.run inside a running loop
Each thread can have only one running loop. Calling asyncio.run from inside a coroutine raises an error.
import asyncio
async def inner():
return 1
async def main():
coro = inner()
try:
asyncio.run(coro)
except RuntimeError as exc:
coro.close()
print("error:", exc)
print("correct way:", await inner())
asyncio.run(main())The message is asyncio.run() cannot be called from a running event loop. Inside async code, use await, create_task, or gather. The same error appears in environments that already run a loop for you, such as Jupyter notebooks and some web framework handlers. In a notebook, write await main() in a cell instead of calling asyncio.run.
Reusing loop-bound objects across runs
Every asyncio.run call creates a fresh loop and closes it at the end. Objects such as locks, queues, events, and open connections can become tied to the loop that first used them. Using them again in a second asyncio.run call can raise errors such as RuntimeError: ... is bound to a different event loop. Create such objects inside the coroutine that runs on the loop, not at module level.
Running several steps on one loop with asyncio.Runner
Sometimes you must run several coroutines from synchronous code and keep them on the same loop. For example, a test suite may set up a connection, run a check, then tear down. Python 3.11 added asyncio.Runner for this.
import asyncio
async def setup():
queue = asyncio.Queue()
await queue.put("ready")
return queue
async def use(queue):
return await queue.get()
with asyncio.Runner() as runner:
queue = runner.run(setup())
print(runner.run(use(queue)))Both calls share one loop, so the queue stays valid between them. When the with block exits, the runner performs the same cleanup as asyncio.run. Plain asyncio.run is in fact a thin wrapper around a runner.
Interrupts, debug mode, and options
On Python 3.11 and later, pressing Ctrl+C while asyncio.run is active cancels the main task first. Your finally blocks and async with exits run, and then KeyboardInterrupt is raised from asyncio.run. On earlier versions the interrupt may land at an arbitrary point, so cleanup is less predictable.
Debug mode adds checks that catch many mistakes. You can enable it in three ways.
- Pass
debug=True:asyncio.run(main(), debug=True). - Set the environment variable
PYTHONASYNCIODEBUG=1. - Start Python with
python -X dev.
In debug mode asyncio logs callbacks and steps that block the loop for more than 100 milliseconds. It also reports coroutines that were never awaited with a traceback showing where they were created. Debug mode slows the program, so use it during development.
Python 3.12 added a loop_factory argument, which lets you choose the loop implementation, for example a faster third-party loop. Most programs never need it.
Choosing the right call
| Situation | Use |
|---|---|
| Script or `main()` entry point | `asyncio.run(main())` |
| Several sync-driven steps sharing one loop | `asyncio.Runner` (3.11+) |
| Inside a coroutine, wait for another coroutine | `await other()` |
| Inside a coroutine, start work without waiting | `asyncio.create_task(other())` |
| Jupyter or another environment with a running loop | `await main()` at the top level |
Practical guidelines
- Keep the entry point small. Put
asyncio.run(main())underif __name__ == "__main__":and put all logic in coroutines. - Parse arguments and configure logging before calling
asyncio.run, since those steps are synchronous. - Create loop-bound resources inside
main(). - Do not call
asyncio.get_event_loop()to start programs. That older pattern behaves differently across Python versions and is deprecated for this purpose. - Make sure every task you start is awaited, gathered, or held in a TaskGroup before
main()returns.
Exercise
A script defines async def main() that starts task = asyncio.create_task(worker()), where worker loops forever printing a line every second. main() sleeps for 3 seconds and returns. The script ends with asyncio.run(main()). Does the program run forever? What happens to worker when main() returns, and what exception does worker see?
Show answer
The program does not run forever. When main() returns, asyncio.run cancels all pending tasks, including worker, and waits for them to finish handling the cancellation. worker receives asyncio.CancelledError at its current await. If it re-raises the exception (or does not catch it), the task ends as cancelled and the program exits. If worker caught CancelledError and kept looping, asyncio.run would keep waiting, so cleanup code must re-raise.
Exercise
Why does calling asyncio.run(inner()) inside a coroutine fail, and what should you write instead if you want the result of inner()?
Show answer
The thread already has a running event loop, and asyncio.run refuses to start a second one, raising RuntimeError: asyncio.run() cannot be called from a running event loop. Write result = await inner() to wait for the result, or asyncio.create_task(inner()) if you want it to run concurrently and collect the result later.