liveBook · Manning

Coroutine object

As explained in Python Concurrency with asyncio

A runtime object representing a coroutine computation that has been created but not yet executed to completion.

A coroutine object is created when an async function is called. Unlike a normal function call, it does not execute the coroutine body immediately; it represents work that can run later. section 2.1.1

Run the object explicitly on an event loop, commonly with asyncio.run. Awaiting a coroutine starts it and pauses the containing coroutine until a result is available. section 2.1.1 section 2.1.2

Calling versus running

Calling coroutine_add_one(1) produces a coroutine object rather than the integer result. Passing that call to asyncio.run executes it and returns 2; calling asyncio.sleep alone likewise produces a coroutine object. section 2.1.1 section 2.2

Listing 2.2 Comparing coroutines to normal functions
async def coroutine_add_one(number: int) -> int:
    return number + 1
 
 
def add_one(number: int) -> int:
    return number + 1
 
 
function_result = add_one(1)
coroutine_result = coroutine_add_one(1)
 
print(f'Function result is {function_result} and the type is {type(function_result)}')
print(f'Coroutine result is {coroutine_result} and the type is {type(coroutine_result)}')

Compare a normal function result with the coroutine object returned by an async function. section 2.1.1

How Python Concurrency with asyncio covers it

How deep it goes
Defines creation, explicit execution, and awaiting, but defers fuller treatment of awaitables.
Examples
Uses integer addition, asyncio.run, asyncio.sleep, and a reusable delay coroutine to demonstrate coroutine objects.
What it assumes
Assumes basic Python function calls while introducing async functions, coroutine objects, and event-loop execution.
What you can do after
Operate/configure coroutine execution by passing coroutine objects to asyncio.run or awaiting them inside another coroutine.
How it connects
Connects coroutine objects with async functions, event loops, await, awaitables, and asyncio.sleep.

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.