WE CODE NOW
  • Home 
  • Blog 
  • Guides 
Guides
  1. Home
  2. Guides
  3. Python Programming
  4. Asynchronous Programming with Asyncio

Asynchronous Programming with Asyncio

Posted on June 1, 2024  (Last modified on June 8, 2024) • 2 min read • 246 words
Python
 
Asyncio
 
Asynchronous
 
Coroutines
 
Python
 
Asyncio
 
Asynchronous
 
Coroutines
 
Share via

Learn the basics of asynchronous programming in Python using the `asyncio` module, including coroutines, tasks, and event loops.

On this page
  • Coroutines
    • Defining a Coroutine
  • Tasks
    • Creating and Running Tasks
  • Event Loops
    • Running an Event Loop
  • Handling Exceptions
    • Catching Exceptions in Coroutines
  • Conclusion

Asynchronous Programming with Asyncio  

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.

Coroutines  

Defining a Coroutine  

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())

Tasks  

Creating and Running Tasks  

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())

Event Loops  

Running an Event Loop  

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()

Handling Exceptions  

Catching Exceptions in Coroutines  

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())

Conclusion  

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.

 Building Command-Line Interfaces (CLI) with Python
Unit Testing in Python with Unittest 
On this page:
  • Coroutines
    • Defining a Coroutine
  • Tasks
    • Creating and Running Tasks
  • Event Loops
    • Running an Event Loop
  • Handling Exceptions
    • Catching Exceptions in Coroutines
  • Conclusion
Copyright © 2024 WE CODE NOW All rights reserved.
WE CODE NOW
Link copied to clipboard
WE CODE NOW
Code copied to clipboard