---
title: "Python asyncio Tutorial: A Beginner’s Guide"
description: "Find out how to properly use the asyncio library for asynchronous programming and when is the best time to do so."
url: "https://iproyal.com/blog/python-asyncio-tutorial/"
---

- [EN - English](https://iproyal.com/)
   
  [中文 - Chinese](https://iproyal.cn/)

[Book a Demo](https://iproyal.com/request-a-demo/) [Create Account](https://dashboard.iproyal.com/register/) [Create Account](https://dashboard.iproyal.com/register/) [Login](https://dashboard.iproyal.com/login/) [Login](https://dashboard.iproyal.com/login/)

[Book a Demo](https://iproyal.com/request-a-demo/)

[Back to blog](https://iproyal.com/blog/)

# Python asyncio Tutorial: A Beginner’s Guide

[Eugenijus Denisov](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Last updated - April 3, 2025 ‐ 7 min read](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Python](https://iproyal.com/blog/category/python/)

Python’s *asyncio* is **the primary library for enabling asynchronous programming features.&#x20;**&#x49;n simple terms, synchronous programming executes each line in turn, waiting for the task to complete before executing another line.

Asynchronous programming, on the other hand, can be used to **execute a function and continue with other tasks while the former one waits for completion.&#x20;**&#x41;s such, asynchronous programming is extremely popular in various network functions, numerous applications, file I/O tasks, APIs, and much more.

Learning how to use *asyncio* properly is part of becoming a good Python developer as you’ll likely use it frequently throughout your career.

## What is Python asyncio?

It’s an in-built library with a few key features, namely **coroutines, tasks, and event loops.&#x20;**&#x45;ach of these is used to create asynchronous code, which can be used to execute several functions simultaneously.

**Event loop&#x20;**: One of the core features. Everything else is nested in the event loop, which itself ensures that coroutines and tasks can be executed effectively. The event loop performs constant monitoring, scheduling, and dispatching.

**Coroutine&#x20;**: A special function that’s defined with *async def* instead of a regular *def.* Its unique feature is that it can pause execution with the *await* keyword.

**Task&#x20;**: A wrapper for a coroutine. When a coroutine is scheduled in an event loop, it gets converted to a task for easier management.

## Example of Synchronous vs Asynchronous Programming in Python

You can write two formally identical functions in both synchronous and asynchronous programming principles. **The only difference between them is how they’ll be executed and the *asyncio* syntax.**

Here’s how synchronous code would look like:

```python
import time

def fetch_data():
    print("Fetching data...")
    time.sleep(2)  # Simulates a blocking I/O operation
    print("Data fetched")

def main():
    fetch_data()
    fetch_data()

if __name__ == "__main__":
    main()
```

In this application, no Python *asyncio* is used, so **the code executes each line after the other.&#x20;**&#x53;ince it’ll run the *main* function, it’ll run *fetch\_data()* once and wait until the function completes, then run the second iteration.

On the other hand, here’s how asynchronous code might look like:

```python
import asyncio

async def fetch_data():
    print("Fetching data...")
    await asyncio.sleep(2)  # Non-blocking sleep
    print("Data fetched")

async def main():
    await asyncio.gather(fetch_data(), fetch_data())

if __name__ == "__main__":
    asyncio.run(main())
```

When the *asyncio* event loop is run, **both iterations of *fetch\_data()* are executed almost simultaneously.&#x20;**&#x49;f the functions were real data extraction actions, you might get the results almost at the same time instead of one after the other.

In more mathematical terms, synchronous programming will deliver the final results as a sum of all function delays, while **asynchronous programming will deliver the final results closer to the longest individual delay.**

## Setting Up asyncio in Python

Since Python *asyncio* is a default library, **no installation is required.&#x20;**&#x41;s long as you have Python itself and IDE, you can start using *asyncio* right off the bat.

Like with any library, to create *async* functions, you’ll need to **import the library first:**

```python
import asyncio
```

That’s all you need to do to create *async* functions. But to make use of them, however, you’ll need to **set up an event loop.**

As mentioned previously, you’ll have to define an asynchronous function, which is done by adding the *async* keyword before the *def* keyword. Additionally, you can’t just call the function regularly - **it has to be wrapped in *asyncio* for the event loop to perform properly.**

```python
import asyncio


async def main():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

asyncio.run(main())
```

While the function will run an event loop and perform asynchronous tasks, it’ll be hard to notice differences. In fact, since we’re using sleep but have no other asynchronous event loop, **the execution may be slower than a synchronous one.**

To showcase the power of asynchronous programming, we can use a **function with an event loop and several coroutines that return some text after completion.&#x20;**&#x57;e’ll also run a nearly identical function but with synchronous programming:

```python
import asyncio
import time


# Asynchronous task that simulates an I/O-bound operation.
async def async_task(delay):
    await asyncio.sleep(delay)
    return f"Task with {delay}s delay completed"


# Run tasks concurrently using asyncio.gather.
async def run_async_tasks():
    start = time.perf_counter()
    # All tasks start at the same time.
    results = await asyncio.gather(
        async_task(2),
        async_task(2),
        async_task(2)
    )
    end = time.perf_counter()
    print(f"Asynchronous tasks completed in {end - start:.2f} seconds")
    for result in results:
        print(result)


# Synchronous version: tasks run sequentially.
def run_sync_tasks():
    start = time.perf_counter()
    # Each sleep happens one after another.
    time.sleep(2)
    print("Task with 2s delay completed")
    time.sleep(2)
    print("Task with 2s delay completed")
    time.sleep(2)
    print("Task with 2s delay completed")
    end = time.perf_counter()
    print(f"Synchronous tasks completed in {end - start:.2f} seconds")


if __name__ == "__main__":
    print("Running synchronous tasks:")
    run_sync_tasks()
    print("\nRunning asynchronous tasks:")
    asyncio.run(run_async_tasks())
```

You can simply **copy and paste and run the code.&#x20;**&#x49;t’ll start by completing the synchronous tasks and print out the completion time. Then, the asynchronous tasks will be run, and the completion time will be output.

In most cases, the synchronous tasks will complete in about 6 seconds, while the asynchronous tasks will complete in about 2 seconds.

## Key Functions and Features of Python asyncio

To make the best use of Python’s *asyncio* library, you’ll need to understand just a few key functions and features. While we have discussed coroutines, asynchronous tasks, and event loops, **they have to be implemented properly.**

- *async def* – defines a coroutine
- *await* – pauses the coroutine until the awaited task is completed.

We’ve used both in our “Hello World” function above. To make use of asynchronous programming, however, we’ll have to **look into methods like *asyncio.gather()* and *asyncio.run()*&#x20;**.

Gather is a simple method that allows you to run multiple coroutines in your async functions. To run multiple coroutines, all you need to do is **add them as arguments in your gather method.**

```python
import asyncio

async def fetch_data(delay):
    await asyncio.sleep(delay)
    return f"Data fetched after {delay} seconds"

async def main():
    results = await asyncio.gather(
        fetch_data(2),
        fetch_data(3),
        fetch_data(1)
    )
    print(results)

asyncio.run(main())
```

On the other hand, the *run* method is a higher-level API that creates an event loop and runs coroutines. Notice that **the *gather* method is used to wrap coroutines while *run* executes the entire *main* function.**

## Practical Examples of Python asyncio

If you’re planning to get involved with networking, APIs, apps, or file operations, you’ll likely be using Python *asyncio* all the time. A great application for the library is **sending asynchronous HTTP requests to multiple APIs&#x20;**&#x74;o reduce overall latency:

```python
import asyncio
import aiohttp  # Ensure you install aiohttp with: pip install aiohttp

async def fetch_url(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = [
        "https://api.example.com/data1",
        "https://api.example.com/data2",
        "https://api.example.com/data3",
    ]
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_url(session, url) for url in urls]
        responses = await asyncio.gather(*tasks)
        for response in responses:
            print(response[:100])  # Print the first 100 characters of each response

if __name__ == "__main__":
    asyncio.run(main())
```

So, instead of having to wait for each of the calls to complete, you’ll get the results almost simultaneously.

While printing API responses doesn’t seem like a useful application for asynchronous tasks, **it’s quite widely used for data retrieval to a single point.**

On the other hand, there’s a necessity to sometimes manipulate several files at once. While the default Python *asyncio* library can’t interact with files properly, **there are good third-party ones:**

```python
import asyncio
import aiofiles  # Install using: pip install aiofiles

async def read_file(filename):
    async with aiofiles.open(filename, mode='r') as f:
        content = await f.read()
        print(f"Content of {filename}:\n{content}\n")

async def main():
    files = ["file1.txt", "file2.txt"]
    await asyncio.gather(*(read_file(file) for file in files))

if __name__ == "__main__":
    asyncio.run(main())
```

## Asynchronous Programming vs Threading vs Multiprocessing

All three can be put under the umbrella term "concurrency". They’re ways to execute code simultaneously, all with unique applications and use cases.

1\. **Asynchronous programming&#x20;**&#x63;reates a single CPU thread and uses *await* to pause a coroutine while waiting for a response, allowing other tasks to be executed. One of the major benefits is that the code is nearly identical to synchronous code.

2\. **Threading&#x20;**&#x63;reates multiple threads that run concurrently in the same memory space, managed by the operating system. Great for some I/O applications, however, the Python Global Interpreter Lock (GIL) can make it difficult to implement properly, and sometimes, performance gains may not be realized.

3\. **Multiprocessing&#x20;**&#x63;reates separate processes with the goal of bypassing the GIL lock. Perfect for CPU-intensive tasks as it provides true parallelism, but is more resource intensive and creates significant overhead.

| Aspect | Asyncio | Threading | Multiprocessing |
| - | - | - | - |
| Execution Model | Single-threaded event loop; cooperative multitasking | Multiple threads; preemptive multitasking | Multiple processes; true parallelism |
| Best For | I/O tasks, network servers, high concurrency, APIs | I/O-bound tasks that require shared state | Heavy computation and CPU-bound tasks |
| Overhead | Low overhead (minimal context switching) | Moderate (thread creation and context switching) | High (process creation and IPC overhead) |
| Memory | Single memory space | Shared memory space | Separate memory spaces, more isolated |
| GIL Impact | Not applicable (single-threaded) | Affected by GIL (limits CPU-bound performance) | Not affected by GIL |

## Debugging asyncio Code

**Python’s *asyncio* is a little harder to debug as there are tasks running at once.&#x20;**&#x53;ometimes you may get hidden inefficiencies that are hard to spot at first glance. Luckily, there are a few good solutions.

First, is to **use the *run* method with the argument *debug=True*.&#x20;**&#x44;oing so provides detailed logs of execution, which can often help uncover inefficiencies or issues with coroutines and tasks.

There are also additional tools like *asyncio.Task.all\_tasks()* that allow you to **inspect running tasks.&#x20;**&#x59;ou could also use third-party debugging tools for additional information.

Finally, it’s recommended to **avoid various blocking functions inherited from synchronous programming&#x20;**&#x73;uch as *time.sleep()*, and use the tools provided by *asyncio* instead (such as *await asyncio.sleep()*).

[Create Account](https://dashboard.iproyal.com/)

[Author](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Eugenijus Denisov](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Lead Backend Developer](https://iproyal.com/blog/authors/eugenijus-denisov/)

With over a decade of experience under his belt, Eugenijus has worked on a wide range of projects - from LMS (learning management system) to large-scale custom solutions for businesses and the medical sector. Proficient in PHP, Vue.js, Docker, MySQL, and TypeScript, Eugenijus is dedicated to writing high-quality code while fostering a collaborative team environment and optimizing work processes. Outside of work, you’ll find him running marathons and cycling challenging routes to recharge mentally and build self-confidence.

[Learn More About Eugenijus Denisov ](https://iproyal.com/blog/authors/eugenijus-denisov/)[Meet all Writers](https://iproyal.com/blog/authors/)

Share on

### In This Article

- [What is Python asyncio?](https://iproyal.com/blog/python-asyncio-tutorial/#What-is-Python-asyncio)
- [Example of Synchronous vs Asynchronous Programming in Python](https://iproyal.com/blog/python-asyncio-tutorial/#Example-of-Synchronous-vs-Asynchronous-Programming-in-Python)
- [Setting Up asyncio in Python](https://iproyal.com/blog/python-asyncio-tutorial/#Setting-Up-asyncio-in-Python)
- [Key Functions and Features of Python asyncio](https://iproyal.com/blog/python-asyncio-tutorial/#Key-Functions-and-Features-of-Python-asyncio)
- [Practical Examples of Python asyncio](https://iproyal.com/blog/python-asyncio-tutorial/#Practical-Examples-of-Python-asyncio)
- [Asynchronous Programming vs Threading vs Multiprocessing](https://iproyal.com/blog/python-asyncio-tutorial/#Asynchronous-Programming-vs-Threading-vs-Multiprocessing)
- [Debugging asyncio Code](https://iproyal.com/blog/python-asyncio-tutorial/#Debugging-asyncio-Code)

Ready to get started?

[Register now](https://dashboard.iproyal.com/register/)

Data News in Your Inbox

No spam whatsoever, just pure data gathering news, trending topics and useful links. Unsubscribe anytime.

No spam. Unsubscribe anytime.

## Related articles

[View all](https://iproyal.com/blog/category/python/)

[Python](https://iproyal.com/blog/parsing-reading-writing-json-with-python/)

## [How to Parse JSON in Python: Read, Write & Work With JSON Files](https://iproyal.com/blog/parsing-reading-writing-json-with-python/)

[Learn how to read, write, and parse JSON in Python using the built-in JSON module and custom classes for clean, efficient data handling.](https://iproyal.com/blog/parsing-reading-writing-json-with-python/)

[January 31, 2023](https://iproyal.com/blog/parsing-reading-writing-json-with-python/)

[9 min read](https://iproyal.com/blog/parsing-reading-writing-json-with-python/)

[Python](https://iproyal.com/blog/python-syntax-errors/)

## [Python Syntax Errors: What They Are and How to Fix Them](https://iproyal.com/blog/python-syntax-errors/)

[Find out why you get syntax errors and how you can fix them quickly and effectively.](https://iproyal.com/blog/python-syntax-errors/)

[October 24, 2024](https://iproyal.com/blog/python-syntax-errors/)

[6 min read](https://iproyal.com/blog/python-syntax-errors/)

[Python](https://iproyal.com/blog/python-xml-parsing/)

## [Python XML Parsing: Full Guide](https://iproyal.com/blog/python-xml-parsing/)

[Find out how to use Python to parse XML files effectively and what are the most popular libraries for the job.](https://iproyal.com/blog/python-xml-parsing/)

[November 25, 2024](https://iproyal.com/blog/python-xml-parsing/)

[9 min read](https://iproyal.com/blog/python-xml-parsing/)
