How to use async and await with Python?

Sometimes, we want to use async and await with Python to run async tasks.

In this article, we’ll look at how to use async and await with Python.

How to use async and await with Python?

To use async and await with Python, we can use the asyncio module and the async and await keywords.

For instance, we write:

import asyncio


async def async_foo():
    print("async_foo started")
    await asyncio.sleep(1)
    print("async_foo done")


async def main():
    asyncio.ensure_future(async_foo())
    print('Do some actions 1')
    await asyncio.sleep(1)
    print('Do some actions 2')
    await asyncio.sleep(1)
    print('Do some actions 3')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

We define the async async_foo function which prints some text and calls asyncio.sleep to pause the function for 1 second.

Then we have the async main function that asyncio.ensure_future method to create a task from the async_foo function and run it.

And then we call asyncio.sleep again with await to pause the function.

Next, we call asyncio.get_event_loop to return the event loop object.

And then we call loop.run_until_complete with main() to run main.

Therefore, we see:

Do some actions 1
async_foo started
Do some actions 2
async_foo done
Do some actions 3

printed with some pauses in between printing each line.

Conclusion

To use async and await with Python, we can use the asyncio module and the async and await keywords.