A Quick Introduction to Asyncio in Python3

Python has never been the best at doing multiple things at the same time.

While there are ways to mostly resolve this, such as using the Multiprocessing library, it always seems a bit make-shift to me.

So many other languages have fantastic ways of resolving these types of issues, and Python now has an Async way too!

Introducing Asyncio

Asyncio is a library to write concurrent code using the async/await syntax.

https://docs.python.org/3/library/asyncio.html

The easiest way to get started is to simply try this out:

import asyncio

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

# Python 3.7+
asyncio.run(main())

If you are running a Python version less than 3.7, then you will need to substitute asyncio.run(main()) with the following:

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

Otherwise you will get an error that says: AttributeError: module 'asyncio' has no attribute 'run'

Breaking it down

So if we break this small code snippet down, we can see that:

  1. We need to import the asyncio module
  2. We need to wrap the code we want to run asyncronously into a function
  3. We add the keyword async before the function name we will call
  4. We call our asynchronous function within an asyncio.run() call

This seems pretty easy.

There are additional functions we can call such as asyncio.sleep(1) to pause the processing.

Note how when we do this, we prepend the await keyword to the call.

Tags:
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments