What is Async?
Asynchronous programming allows your program to handle multiple tasks concurrently without threads. Python3 provides the asyncio module.
async/await Basics
import asyncio
async def say_hello():
print("Hello...")
await asyncio.sleep(1)
print("World!")
asyncio.run(say_hello())
Concurrent Tasks
import asyncio
async def fetch_data(name, delay):
await asyncio.sleep(delay)
return f"{name} data"
async def main():
results = await asyncio.gather(
fetch_data("users", 2),
fetch_data("posts", 1),
fetch_data("comments", 3)
)
print(results)
asyncio.run(main())
Summary
- async def defines a coroutine function
- await pauses execution until the coroutine completes
- asyncio.gather() runs multiple coroutines concurrently
YouTip