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
- Define coroutines with
async def. - Use
awaitto call other coroutines. - 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()orasyncio.create_task(). awaitcan only be used insideasync deffunctions.- Use
async forandasync withfor asynchronous iterables and context managers. - For CPU-bound work, use
concurrent.futures.ProcessPoolExecutorinstead 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 deffunction withoutawaitreturns a coroutine object, not the result. - Blocking calls (like
time.sleep()) inside a coroutine freeze the event loop; useasyncio.sleep()instead. asyncio.run()cannot be called from a running event loop or from within another coroutine in some contexts.