How do I get started with asyncio and async/await in Python?

· Category: Python Programming

Short answer

asyncio is Python's standard library for writing concurrent code using the async/await syntax. It uses an event loop to manage coroutines, making it ideal for I/O-bound tasks like network requests.

Steps

  1. Define coroutines with async def.
  2. Use await to call other coroutines.
  3. Run the top-level coroutine with asyncio.run().
import asyncio

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    await say_after(1, "hello")
    await say_after(2, "world")

asyncio.run(main())

Tips

  • Run coroutines concurrently with asyncio.gather() or asyncio.create_task().
  • await can only be used inside async def functions.
  • Use async for and async with for asynchronous iterables and context managers.
  • For CPU-bound work, use concurrent.futures.ProcessPoolExecutor instead of asyncio threads.
async def main():
    await asyncio.gather(
        say_after(1, "first"),
        say_after(2, "second")
    )

asyncio.run(main())

Common issues

  • Calling an async def function without await returns a coroutine object, not the result.
  • Blocking calls (like time.sleep()) inside a coroutine freeze the event loop; use asyncio.sleep() instead.
  • asyncio.run() cannot be called from a running event loop or from within another coroutine in some contexts.