Python's asyncio module provides infrastructure for writing concurrent code using the async/await syntax. So while asyncio is not a part of the Python standard library, it is included with Python 3.7 and higher.
Why Async IO?
The async/await keywords in Python enable a paradigm called asynchronous programming. This allows you to write non-blocking code that can efficiently utilize I/O resources without causing the program to wait.
Some key benefits of asyncio:
Let's look at a quick example:
import asyncio
async def fetch_data():
print('start fetching')
await asyncio.sleep(2) # simulate a 2 second delay
print('done fetching')
return {'data': 1}
async def print_numbers():
for i in range(10):
print(i)
await asyncio.sleep(0.25)
async def main():
task1 = asyncio.create_task(fetch_data())
task2 = asyncio.create_task(print_numbers())
value = await task1
print(value)
await task2
asyncio.run(main())
This concurrently runs two async functions without blocking the main thread.
How to Use Asyncio
The
The key takeaways are:
So while asyncio is not part of the Python standard library, it is included with Python by default. This makes async programming a built-in capability of the language.