1️⃣ async def foo()
-
This defines an asynchronous function.
-
Calling foo() does NOT execute it immediately.
-
It returns a coroutine object.
2️⃣ asyncio.run(foo())
asyncio.run(foo())asyncio.run():
-
Creates an event loop
-
Executes the coroutine foo()
-
Waits until it finishes
-
Returns the final result
-
✅ Since foo() returns 5, this line evaluates to:
53️⃣ + 1
asyncio.run(foo()) + 1-
Now it becomes:
-
Result:
4️⃣ print(...)
print(6)✅ Final Output
6⚠️ Important Trick
If you wrote this instead:
print(foo() + 1)❌ It would raise an error because:
foo() returns a coroutine, not an integer
๐ก Key Takeaway
async def → returns a coroutine
asyncio.run() → executes it and returns the result
-
You can only use the returned value after awaiting/running


0 Comments:
Post a Comment