LevelJar Sign in

Python course / Applied

Async syntax and event loops

Write coroutines that wait without blocking, and run many of them at once. Async is about waiting, not speed, and one blocking call freezes every task you started.

  • async and await
  • gather
  • tasks
  • timeouts
  • cancellation
  • TaskGroup
  • queues
  • semaphores

Start this module

Runs in your browser. Start straight away; create an account when you want your progress kept.

three waits, one second
import asyncio
import time


async def fetch(name, seconds):
    await asyncio.sleep(seconds)
    return f"{name} after {seconds}s"


async def main():
    started = time.perf_counter()
    results = await asyncio.gather(
        fetch("tea", 1), fetch("jam", 1), fetch("oats", 1)
    )
    for line in results:
        print(line)
    print(f"elapsed: {time.perf_counter() - started:.1f}s")


asyncio.run(main())
tea after 1s
jam after 1s
oats after 1s
elapsed: 1.0s

What you will learn

The lessons in this module

  • Waiting, not working
  • A coroutine is an object
  • Awaiting in sequence
  • gather: waiting on several at once
  • Tasks: starting work now
  • An event loop by hand
  • Blocking the loop
  • Timeouts
  • Cancellation
  • Errors in gather
  • TaskGroup: all or nothing
  • Queues: sharing out the work
  • Limiting how many at once
  • async with and async for
  • Capstone: a polite crawler
  • Module review: the order board

Ready when you are

Start this module

Previous: functools and itertools. Next: Testing. All modules are on the course page.