liveBook · Manning

Asyncio.run

As explained in Python Concurrency with asyncio

asyncio.run is a high-level function that executes an asynchronous entry-point coroutine in a newly managed event loop and performs shutdown cleanup.

asyncio.run is the usual entry point for an asyncio application. It creates a new event loop, runs one supplied coroutine until it completes, returns its result, cleans up remaining asynchronous work, and closes the loop. section 2.1.1

Running a coroutine

import asyncio async def coroutine_add_one(number: int) -> int: return number + 1 result = asyncio.run(coroutine_add_one(1)) print(result) # 2 Calling the coroutine directly would create a coroutine object without executing its body. asyncio.run places it on an event loop and executes it. section 2.1.1

Use asyncio.run as the boundary between synchronous startup code and asynchronous application work:

  • Pass one main coroutine; have that coroutine create and coordinate the application's other coroutines and tasks. section 2.1.1
  • Enable diagnostics with asyncio.run(coroutine(), debug=True) when investigating common asyncio problems. section 2.9.1 section 2.10
  • Prefer it for ordinary loop setup, but manage the event loop directly when shutdown behavior or low-level scheduling requires custom control. section 2.8 section 3.6.2
Listing 2.3 Running a coroutine
import asyncio
 
 
async def coroutine_add_one(number: int) -> int:
    return number + 1
 
 
result = asyncio.run(coroutine_add_one(1))
 
print(result)

A minimal runnable listing shows the complete pattern: define a coroutine, pass its invocation to asyncio.run, and consume the returned result. section 2.1.1

How Python Concurrency with asyncio covers it

How deep it goes
Explains loop creation, coroutine execution, cleanup, shutdown, and debug mode, while deferring custom low-level control to manual management.
Examples
Uses coroutine_add_one(1), debug=True, custom graceful shutdown, and one event loop per process.
What it assumes
Builds from coroutine objects and event-loop execution, contrasting asynchronous functions with ordinary functions.
What you can do after
Apply it via asyncio to launch an asynchronous application's main coroutine and receive its completed result.
How it connects
Connects coroutines, event loops, tasks, cancellation, timeouts, and process pools.

Also explained in

Compare how 2 books explain asyncio.run →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.