Asynchronous Python refers to a style of programming that allows you to write code that can perform multiple operations at the same time, without having to wait for each operation to complete before starting the next one. This is particularly useful for I/O-bound and high-latency activities, such as web requests, database operations, reading and writing files, etc., where the application can stay productive while waiting for these activities to complete.
In Python, asynchronous programming is achieved using the asyncio library, which is included in the standard library from Python 3.5 onwards. The key concepts of asynchronous programming in Python are async functions (coroutines), the await keyword, the event loop, and Future and Task objects.
Here's a basic rundown of how to use asynchronous Python with asyncio:
- Import
asyncio:
import asyncio
- Define
async functions (coroutines) using the async keyword:
async def my_async_function():
# This function can perform asynchronous operations
pass
- Within an
async function, you can call other async functions using await, which yields control back to the event loop until the awaited function completes:
async def another_async_function():
await my_async_function()
print("my_async_function has completed")
- To run asynchronous code, you need to get an event loop and use it to execute the coroutines:
async def main():
await another_async_function()
# Python 3.7+
asyncio.run(main())
# Older versions of Python (prior to 3.7)
# loop = asyncio.get_event_loop()
# loop.run_until_complete(main())
# loop.close()
A complete example might look like this:
import asyncio
async def fetch_data():
print("Start fetching data")
await asyncio.sleep(2) # Simulate I/O by sleeping for 2 seconds
print("Done fetching data")
return {'data': 1}
async def print_numbers():
for i in range(10):
print(i)
await asyncio.sleep(0.25) # Sleep for 0.25 seconds
async def main():
# Schedule both the coroutines to run concurrently
task1 = asyncio.create_task(fetch_data())
task2 = asyncio.create_task(print_numbers())
# Wait until both tasks are completed
data = await