Run a Bounded Async Program
Core idea
An event loop coordinates runnable tasks and I/O notifications. asyncio.run(main()) creates and manages a loop for a top-level coroutine in Python 3.13 and returns its result. Within a coroutine use get_running_loop() to inspect the active loop. Await does not always suspend: a ready result may be delivered immediately.
import asyncioasync def main(): loop = asyncio.get_running_loop() print(loop.is_running()) return 'done'print(asyncio.run(main()))The loop is running inside main; the result reaches synchronous code.
Expected output:
TruedoneYield without a timed wait
import asyncio
async def main(): print('before') await asyncio.sleep(0) print('after')
asyncio.run(main())sleep(0) suspends the task, giving the loop a chance to run other work.
Expected output:
beforeafterCommon mistake
Do not nest asyncio.run inside a running loop in the same thread. In an async environment await the coroutine instead. Blocking CPU work or synchronous I/O monopolizes the loop thread.
Practice
Return a numeric summary from main and print it outside asyncio.run; explain why sleep(0) is not a timing guarantee.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Event loop and run
Check your understanding of event loop and run.
What is printed?
import asyncioasync def main(): return 5print(asyncio.run(main()))What is printed?
import asyncio
async def main(): print(asyncio.get_running_loop().is_running())
asyncio.run(main())Where should asyncio.run normally be used?
Does every await necessarily yield to another task?