Back
+15 XP
Concept

Executing Async Tasks: asyncio.run()

`asyncio.run(coro)` is the standard entry point for async Python. It creates a new event loop, runs the coroutine until completion, and cleanly closes all tasks 🚀.

python
import asyncio

async def main():
    print("Event loop initialized 🚀")
    await asyncio.sleep(0.01)
    return "Task Completed"

result = asyncio.run(main())
print(result)  # 'Task Completed' ✅

# 45. Executing Async Tasks: asyncio.run() `asyncio.run(coro)` is the standard entry point for async Python. It creates a new event loop, runs the coroutine until completion, and cleanly closes all tasks 🚀. ```python import asyncio async def main(): print("Event loop initialized 🚀") await asyncio.sleep(0.01) return "Task Completed" result = asyncio.run(main()) print(result) # 'Task Completed' ✅ ``` Always call `asyncio.run()` only once as your main application entry point. Do not call it from inside an already running event loop! 🚀 --- ### Question What is the primary function of `asyncio.run()`? 🧠 - [ ] a. Creates an event loop, runs the given coroutine to completion, and cleans up 🚀 - [ ] b. Spawns a new Docker container with async runtime support - [ ] c. Forces Python to compile async code into C++ threads - [ ] d. Locks the CPU clock speed at maximum frequency --- ### Challenge Write an async function `greet_async(name)` that returns `f'Hello, {name}!'`. Run it with `asyncio.run()` and print the result for `'World'`. 🎯 <details> <summary>Solution</summary> ```python import asyncio async def greet_async(name): return f"Hello, {name}!" result = asyncio.run(greet_async("World")) print(result) ``` </details>

Checkpoint

What is the primary function of `asyncio.run()`? 🧠

Practice

Write an async function `greet_async(name)` that returns `f'Hello, {name}!'`. Run it with `asyncio.run()` and print the result for `'World'`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks