Distinguish Coroutines from Awaitables
Core idea
Calling an async def function creates a coroutine object without executing its body. Awaiting it inside async code drives it to completion, suspending the current task when necessary. Awaitables include coroutine objects, Tasks and Futures. A coroutine object is single-use; an async function can create a new one each call.
import asyncio
async def main(): async def read(): print('body') return 7 pending = read() print('created') print(await pending)
asyncio.run(main())The body starts only when awaited here.
Expected output:
createdbody7Await a nested call
import asyncio
async def main(): async def units(): return 4 async def total(): return 3 * await units() print(await total())
asyncio.run(main())The inner result becomes an ordinary integer for the multiplication.
Expected output:
12Common mistake
Discarding an unawaited coroutine can emit RuntimeWarning. Do not await the same coroutine object twice; create a new coroutine or share a Task when appropriate.
Practice
Write an async label function; print a marker before awaiting, then print the returned label.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Coroutines and awaitables
Check your understanding of coroutines and awaitables.
What is printed?
import asyncio
async def main(): async def f(): return 8 print(await f())
asyncio.run(main())What is printed?
import asyncio
async def main(): async def f(): print('run') c=f() print('new') await c
asyncio.run(main())What does async def invocation produce?
Can one coroutine object be awaited again after completion?