0
0
PythonHow-ToBeginner · 3 min read

How to Use asyncio in Python: Simple Guide with Examples

Use asyncio in Python by defining async functions and running them with asyncio.run(). Inside these functions, use await to pause execution until asynchronous tasks complete, enabling efficient concurrent code.
📐

Syntax

The basic syntax for using asyncio involves defining asynchronous functions with the async def keyword. Inside these functions, you use await to wait for asynchronous operations to finish without blocking the whole program. To start the asynchronous code, use asyncio.run() with the main async function.

  • async def: Defines an asynchronous function.
  • await: Pauses the function until the awaited task completes.
  • asyncio.run(): Runs the main async function and manages the event loop.
python
import asyncio

async def main():
    await asyncio.sleep(1)  # Waits asynchronously for 1 second

asyncio.run(main())
💻

Example

This example shows how to run two asynchronous tasks concurrently using asyncio. Each task waits for a different amount of time, but both start together, so the total time is about the longest wait, not the sum.

python
import asyncio

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

async def main():
    task1 = asyncio.create_task(say_after(2, 'Hello'))
    task2 = asyncio.create_task(say_after(1, 'World'))

    print('Started tasks')
    await task1
    await task2
    print('Finished tasks')

asyncio.run(main())
Output
Started tasks World Hello Finished tasks
⚠️

Common Pitfalls

Common mistakes when using asyncio include:

  • Calling async functions without await, which returns a coroutine but does not run it.
  • Using blocking code inside async functions, which stops the event loop and defeats concurrency.
  • Not using asyncio.run() to start the event loop in modern Python versions.

Here is an example showing the wrong and right way to call an async function:

python
# Wrong way: calling async function without await
import asyncio

async def greet():
    print('Hello')

async def main():
    greet()  # This does nothing
    await greet()  # Correct way

asyncio.run(main())
Output
Hello Hello
📊

Quick Reference

CommandDescription
async def function():Defines an asynchronous function
await coroutine()Waits for the coroutine to finish without blocking
asyncio.run(main())Runs the main async function and event loop
asyncio.create_task(coro)Schedules a coroutine to run concurrently
asyncio.sleep(seconds)Asynchronous sleep without blocking

Key Takeaways

Define asynchronous functions with async def and use await inside them.
Use asyncio.run() to start your async program and manage the event loop.
Create concurrent tasks with asyncio.create_task() to run multiple operations together.
Avoid blocking calls inside async functions to keep concurrency effective.
Always await async functions to actually run them and get results.