DEV Community

Cover image for Asynchronous programming in Python
Bruno
Bruno

Posted on

Asynchronous programming in Python

pyramid turning

Have you ever wanted to learn how to write asynchronous code, but found it difficult to understand how it all works and how to apply it in Python? Well, let me tell you it is not as difficult as it seems. Just bear with me as we go through the different sides of the pyramid.

๐Ÿค” What is asynchronous programming? And how does it differ from synchronous programming?

will ferrel asking

When we write code, it is typically executed one line at a time, in the sequence in which it was written. This is referred to as synchronous programming. However, there are occasions when we must execute lengthy activities, such as reading data from a file, fetching information from a remote server or API endpoint, or waiting for user input.

Asynchronous programming, on the other hand, allows us to perform these long-running tasks without blocking the rest of our code from executing. Instead of waiting for a task to complete before moving on, we can start the task and then move on to the next line of code. When the task is finished, we can come back to it and continue where we left off.

๐Ÿ Asynchronour programing in Python

In Python, we can write asynchronous programming using external libraries such as asyncio, which I will be using throughout this article.

In order to use asyncio, you need to install (if you are using a version pre-3.7) and import it to your Python project:

  1. Installing asyncio:


pip install asyncio


Enter fullscreen mode Exit fullscreen mode
  1. Importing asyncio:


import asyncio


Enter fullscreen mode Exit fullscreen mode

Now you should be able to use asyncio and all its available functions/methods in your project ๐ŸŽ‰

โš™๏ธ Coroutines

A coroutine is a function that can be paused and resumed during execution.

You define a coroutine using the async keyword.

Take the following example:



async def my_coroutine():
    print("Coroutine started")
    await asyncio.sleep(1)
    print("Coroutine resumed")


Enter fullscreen mode Exit fullscreen mode

In the example above, the coroutine function runs in the following order:

  1. runs print("Coroutine started")
  2. waits (with await) for 1 second until it can resume
  3. runs print("Coroutine resumed)

๐Ÿ”‚ Creating an event loop

In order to run coroutines concurrently, you need to use an event loop. It can manage multiple coroutines at the same time and you can use the asyncio.get_event_loop() method from the asyncio library for that purpose:



async def coroutine_one():
    print("Coroutine started")
    await asyncio.sleep(1)
    print("Coroutine resumed")

async def coroutine_two():
    print("Coroutine two started")
    await asyncio.sleep(2)
    print("Coroutine two resumed")

loop = asyncio.get_event_loop()
loop.run_until_complete(coroutine_one(), coroutine_two())


Enter fullscreen mode Exit fullscreen mode

The code above runs in the following order:

  1. coroutine_one is executed
  2. print("Coroutine started") prints a message stating the coroutine has started
  3. await asyncio.sleep(1) waits for 1 second until it resumes the execution of coroutine_one
  4. print("Coroutine resumed") prints a message stating the coroutine has resumed
  5. coroutine_two is executed
  6. print("Coroutine started") prints a message stating the coroutine has started
  7. await asyncio.sleep(2) waits for 2 seconds until it resumes the execution of coroutine_two
  8. print("Coroutine resumed") prints a message stating the coroutine has resumed
  9. main() function is define and is used to run both coroutines concurrently - simultaneously
  10. an event loop is created using loop = asyncio.get_event_loop()
  11. loop is executed on loop.run_until_complete(coroutine_one(), coroutine_two())
  12. coroutine_one() is executed and runs print("Coroutine started")
  13. coroutine_two() is executed and runs print("Coroutine started")
  14. coroutine_one() waits for 1 second until it can resume
  15. coroutine_two() waits for 2 seconds until it can resume
  16. after both coroutines wait for 1 and 2 seconds to resume, loop finishes executing and returns the results of the loop

๐Ÿ›ฐ Using async/await with external libraries

Imagine you want to work with HTTP requests asynchronously, you can make use of the async and await keywords to make those requests in an asynchronous programming manner. Take the example of the aiohttp library:



import asyncio
import aiohttp

async def get_data():
   async with aiohttp.ClientSession as session:
      async with session.get(url) as response:
         data = response.json()
         return await data

async def main():
   data = await get_data("catsjsonapi.com/cat1")
   print(data)

loop = async.get_event_loop()
loop.run_until_complete(main())


Enter fullscreen mode Exit fullscreen mode

In this example, we are importing the asyncio and aiohttp libraries to make HTTP requests asynchronously. As an overview if the code above, the main() coroutine is executed using loop (the event loop), which executes the get_data() coroutine and then prints the data from the "catsjsonapi.com/cat1" API endpoint as JSON.

๐Ÿ’ญ Final thoughts

boy asking

Working with asynchronous programming in Python can be very useful in various environments/projects, and doing so is quite easy, as we saw throughout this article. All you need to do is import asyncio and make use of its functions, combine with external libraries, and so on.

However, there are other libraries which allow you to write asynchronous code in Python, such as:

Thank you for reading!๐Ÿ‘‹

After having gone through all of these bits and bytes of async programming in Python, you should now be able to apply it in your code. Congratulations ๐Ÿ™Œ and I hope it was helpful for you!๐Ÿ™‚

I'd like to thank you for reading my article and invite you to follow me on Dev.to, as well as my other platforms:

GitHub: https://github.com/bcostaaa01
Twitter: https://twitter.com/bruno2001costa
Enter fullscreen mode Exit fullscreen mode

I look forward to seeing you on my next one!

Until then,
Happy Coding!๐Ÿ‘ฉโ€๐Ÿ’ป

Top comments (0)