Introduction
Asynchronous programming is becoming more important as applications become more complex and require more interactions with external resources. Python's approach to asynchronous programming is through the use of coroutines, which enable non-blocking IO. The async and await keywords were introduced in Python 3.5 to provide convenient syntax for this style of programming. These keywords allow developers to write async code in a way that looks similar to synchronous code, making it easier to understand and maintain. In this tutorial, we will explore the basics of async-await in Python and learn how to write asynchronous code using this syntax.
Table of Contents :
- Python Coroutines
- How to define a Python Coroutine using async keyword
- How to pause a Python Coroutine using await keyword
Python Co routines :
- A Python co-routine is a function that can be paused and resumed at any point using the
yield
keyword. - Co routines are used for asynchronous programming and can be used to write efficient and scalable code that is capable of handling thousands of concurrent I/O-bound connections.
How to define a Python Co-routine using async keyword :
- Python 3.5 introduced a new syntax for defining co-routines using the
async
keyword. - Here's an example of defining a co-routine using the
async
keyword: - Code Sample :
async def my_coroutine():
print('Coroutine starting')
await asyncio.sleep(1)
print('Coroutine ending')
How to pause a Python Co-routine using await keyword :
- In order to pause a co-routine so that it can resume later, we use the
await
keyword. - Here's an example of defining a co-routine and pausing it using the
await
keyword : - Code Sample :
import asyncio
async def my_coroutine():
print('Coroutine starting')
await asyncio.sleep(1)
print('Coroutine ending')
async def main():
print('Main starting')
await my_coroutine()
print('Main ending')
asyncio.run(main())
Explanation :
- In the above example, we define two coroutines -
my_coroutine()
andmain()
. my_coroutine()
prints"Coroutine starting"
, waits for one second usingasyncio.sleep()
, and then prints"Coroutine ending"
.main()
prints "Main starting", callsmy_coroutine()
using the await keyword, and then prints "Main ending".- The
asyncio.run()
method is used to run themain()
coroutine and start the event loop. - When we run this program, it will output "Main starting", then "Coroutine starting", then wait for one second, then output "Coroutine ending", and finally "Main ending".
Prev. Tutorial : Event loop
Next Tutorial : Creating tasks