Fill the blank
Keep the event loop free while a blocking SDK call runs.
import asyncio
import time
def legacy_sdk() -> str:
time.sleep(0.2)
return "ok"
async def main() -> None:
result = await ____
print(result)
asyncio.run(main())Hint 1 of 1
Which helper runs a sync function off the loop?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A asyncio.to_thread(legacy_sdk)
Correct. The call runs in a worker thread and the loop stays responsive.
A blocking call like time.sleep stops the whole event loop and every other request on it. asyncio.to_thread runs the function in a worker thread and gives back an awaitable, so the loop keeps serving while it waits.
Why not the others?
- B
legacy_sdk(). Awaiting a str fails, and the call already blocked the loop. - C
asyncio.sleep(legacy_sdk()). Runs the blocking call first, on the loop. - D
asyncio.create_task(legacy_sdk). create_task needs a coroutine, not a plain function.