Async IO in Python 3

M Shahid Siddiqui
3 min readMay 7, 2020

--

… writing single-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources, running network clients and servers etc.

What is Async Programming?

Imagine you are in a queue at McDonald. You are hungry and wish to get your order served immediately. Unfortunately, there is just one counter and people have to finalise their order, pay, and pick their order before anybody else behind them could proceed. What would be your reaction — Such a waste of time, and tiring process!

But, if they open another counter, will it solve the problem? Actually no. It is called parallel processing. Even in this situation, if the staff at the counter is slow and/or the queue is too long, you will still be frustrated.

What if you could do something else while waiting for the queue.

What you are wishing is that even though there is a queue, if you could put your order in the queue, stop waiting in the queue, and when your order is ready, you are promptly notified.

This is the exact concept of Asynchronous programming. Python introduced it quite late but it is good that it is now available.

More Jargons

asyncio — It is the python module that is required

async/await Keywords

Steps to Achieve It?

Setting Up the Environment

1 Preconditions

The instructions are adapted with MacOs terminal. So Linux users would be at ease too. Windows users might have to be a bit conscious and have to use alternative options to achieve the same results.

The Async module is introduced in Python 3.3, in the year 2012 and so the basic requirement is to have Python 3.3+ installed in the system. Also, we will user virtual environment so Python module venv should also be installed in the system.

Check out this page for more interesting topics

Unique Source of Knowledge

I’ll be using Python3.7 which is installed in my MacOs.

Check the currently installed Python version

$ which python
$ python -V

2 Create Virtual Environment

$ python3.7 -m venv ./py37async_venv
$ source ./py37async_venv/bin/activate
(py37async_venv)$

For Windows machine

# Windows: .\py37async_venv\Scripts\activate.bat

3 Installation

We will install async modules using pip module (pip3 in fact)

$ pip install --upgrade pip aiohttp aiofiles

At the end of the installation, a similar message should be displayed-

Successfully installed aiofiles-0.5.0 aiohttp-3.6.2 async-timeout-3.0.1 multidict-4.7.5 pip-20.1 yarl-1.4.2

Hands-On Example

Wait this space. More is on the way!

More Resources

You can read the official documentation explaining all the functions available in the module here.

Comments

Please share your feedback so that the contents of this article would be improved.

--

--

M Shahid Siddiqui
M Shahid Siddiqui

Written by M Shahid Siddiqui

Tech Savy | IT Enthusiast | Served 14 Years in IT | M.B.M from University of Auckland, New Zealand

No responses yet