Repaso
EspaƱol
PythonIntermediatePY-15

Roughly how long does main() take?

import asyncio

async def main():
    await asyncio.sleep(1)
    await asyncio.sleep(1)
    await asyncio.sleep(1)

asyncio.run(main())

Options

  1. ~1 second
  2. ~3 seconds (Correct option)
  3. ~0 seconds
  4. It never finishes

Answer

~3 seconds

Why

await means: wait here until this finishes, then continue to the next line.

The three sleeps therefore run one after another: 1 + 1 + 1 = 3 seconds.

To run them at the same time, start them together with asyncio.gather; then they wait in parallel and the total is about 1 second.

await asyncio.gather(
    asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1)
)   # ~1 second

Remember

Separate awaits run in sequence; gather runs them concurrently.

Key terms

Practice this question in Repaso