Python's asyncio module opens up a whole new world of asynchronous programming. Instead of waiting for each line of code to finish before moving to the next, asyncio allows you to execute code concurrently. This can result in huge performance gains for I/O-bound applications.
Avoid Blocking the Event Loop
The key to asyncio is the event loop. This loops runs and executes your asynchronous code concurrently. Using regular blocking code can prevent the event loop from running efficiently:
import time
def blocking_task():
time.sleep(1)
print('Blocking task done')
blocking_task()
Blocking the event loop prevents other coroutines from running. The solution is to use
import asyncio
async def nonblocking_task():
await asyncio.sleep(1)
print('Non-blocking task done')
Now this task will yield control back to the event loop so other tasks can run.
Easy Concurrency with asyncio.gather()
Managing concurrency yourself can get complex quicky. Luckily
import asyncio
async def task1():
print('Task 1 start')
await asyncio.sleep(3)
print('Task 1 done')
async def task2():
print('Task 2 start')
await asyncio.sleep(2)
print('Task 2 done')
asyncio.gather(task1(), task2())
There are many more advantages to asyncio like integration with async web frameworks. Overall, asyncio is a game changer for writing high-performance Python applications. Give it a try next time you need concurrency!