Tasks & Concurrency

Preview — 3 of 10 questions

What is the output of the following code?

javascript
import asyncio
import time

async def task(n):
    await asyncio.sleep(n)

async def main():
    start = time.monotonic()
    t1 = asyncio.create_task(task(0.1))
    t2 = asyncio.create_task(task(0.1))
    await t1
    await t2
    elapsed = time.monotonic() - start
    print(elapsed < 0.2)

asyncio.run(main())
ATrue
BTypeError: create_task() missing argument
CUnpredictable.
DFalse

What is the output of the following code?

javascript
import asyncio

async def slow_operation():
    await asyncio.sleep(1)
    return "done"

async def main():
    try:
        result = await asyncio.wait_for(slow_operation(), timeout=0.1)
        print(result)
    except asyncio.TimeoutError:
        print("timed out")

asyncio.run(main())
Adone
Btimed out
CTypeError: wait_for() missing required argument
DThe program hangs until slow_operation() finishes, ignoring the timeout.

Which statement about the following code's behavior is correct?

javascript
import asyncio

async def fails():
    await asyncio.sleep(0.05)
    raise ValueError("boom")

async def succeeds():
    await asyncio.sleep(0.1)
    return "ok"

async def main():
    try:
        await asyncio.gather(fails(), succeeds())
    except ValueError as e:
        print(f"caught: {e}")

asyncio.run(main())
Agather() raises a TypeError because one of its arguments failed.
Bgather() swallows the exception silently, and neither coroutine's result is ever seen.
CThe ValueError from fails() propagates out of gather() and is caught, printing "caught: boom" — but succeeds(), by default, is not automatically cancelled and keeps running in the background even after the exception propagates.
Dgather() automatically cancels succeeds() the instant fails() raises, so succeeds() never actually finishes its sleep.

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.