Asynchronous Programming with Asyncio
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 246 wordsLearn the basics of asynchronous programming in Python using the `asyncio` module, including coroutines, tasks, and event loops.
Asynchronous programming allows you to run tasks concurrently, improving performance. This guide covers the basics of asynchronous programming in Python using the asyncio
module, including coroutines, tasks, and event loops.
import asyncio
async def hello():
print("Hello, World!")
# Running the coroutine
asyncio.run(hello())
Coroutines can also include delays.
async def delayed_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(delayed_hello())
async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
async def main():
task1 = asyncio.create_task(say_hello())
task2 = asyncio.create_task(say_hello())
await task1
await task2
asyncio.run(main())
Tasks allow you to manage and run multiple coroutines concurrently.
async def fetch_data():
print("Fetching data...")
await asyncio.sleep(2)
print("Data fetched")
async def process_data():
print("Processing data...")
await asyncio.sleep(1)
print("Data processed")
async def main():
await asyncio.gather(fetch_data(), process_data())
asyncio.run(main())
async def print_numbers():
for i in range(5):
print(i)
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
loop.run_until_complete(print_numbers())
loop.close()
Event loops can manage multiple tasks.
loop = asyncio.get_event_loop()
tasks = [print_numbers(), fetch_data()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
async def divide(a, b):
try:
result = a / b
print(f"Result: {result}")
except ZeroDivisionError:
print("Cannot divide by zero")
asyncio.run(divide(1, 0))
Exceptions in tasks can be caught and handled.
async def safe_task():
try:
await divide(1, 0)
except Exception as e:
print(f"Caught an exception: {e}")
asyncio.run(safe_task())
Asynchronous programming with asyncio
allows you to run tasks concurrently, improving performance and responsiveness. Practice using coroutines, tasks, and event loops to handle asynchronous operations in your Python projects.