Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 8 · Async correctness patternsasyncio.shield — let the inner work finish even when the outer awaiter walks awaypredict127 / 161
+150 XP
Task
📝 **Task:** Predict the exact output. The inner task takes ~10ms; the wait_for times out at 1ms. The shield prevents the timeout from cancelling the inner work. The outer 'try' branch sees TimeoutError; meanwhile the inner task keeps running in the background and completes during the trailing sleep. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

import asyncio


results: list[str] = []


async def critical(name: str) -> str:
    await asyncio.sleep(0.01)
    results.append(name)
    return name


async def main() -> None:
    t = asyncio.create_task(critical("commit"))
    try:
        out = await asyncio.wait_for(asyncio.shield(t), timeout=0.001)
        print(f"got {out}")
    except asyncio.TimeoutError:
        print("timeout")

    # Give the shielded task time to finish in the background.
    await asyncio.sleep(0.05)
    print(f"results: {results}")
    print(f"task done: {t.done()}")


asyncio.run(main())

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…