Asynchronous Processing in Python
This article explains asynchronous processing in Python.
You can learn code samples for the basic usage of Python's async/await and the asyncio module.
YouTube Video
Asynchronous Processing in Python
Asynchronous processing in Python is a mechanism for efficiently handling time-consuming I/O operations, such as reading and writing files or network communication. In synchronous processing, the next operation waits until the current one finishes, but with asynchronous processing, you can proceed with other tasks during the waiting time. In Python, the asyncio module is provided for performing asynchronous processing. Here, we will explain its basic elements and how to use them step by step.
Basic Syntax
At the core of asynchronous processing are functions called coroutines. async functions define asynchronous functions, and await is used to wait for an asynchronous task within those functions.
1import asyncio
2
3async def say_hello():
4 print("Hello")
5 await asyncio.sleep(1)
6 print("World")
7
8if __name__ == "__main__":
9 # Execute asynchronous task
10 asyncio.run(say_hello())- In the above code, the
say_hellofunction is defined as an asynchronous task. While waiting for 1 second withsleep(), other asynchronous tasks may be executed.
Executing Multiple Tasks
By using the gather function of the asyncio module, you can run multiple tasks simultaneously.
1import asyncio
2
3async def task1():
4 print("Task 1 started")
5 await asyncio.sleep(2)
6 print("Task 1 completed")
7
8async def task2():
9 print("Task 2 started")
10 await asyncio.sleep(1)
11 print("Task 2 completed")
12
13async def main():
14 await asyncio.gather(task1(), task2())
15
16if __name__ == "__main__":
17 asyncio.run(main())- In this example,
task1andtask2are executed concurrently. As a result,task2completes first of the two tasks, but the total execution time equals the longest task's execution time.
Error Handling
Error handling is important even in asynchronous processing. You can catch and handle errors using the standard try-except syntax.
1import asyncio
2
3async def faulty_task():
4 raise Exception("An error occurred")
5
6async def main():
7 try:
8 await faulty_task()
9 except Exception as e:
10 print(f"Caught an error: {e}")
11
12if __name__ == "__main__":
13 asyncio.run(main())- This code demonstrates how exceptions occurring inside asynchronous functions can be caught with
try-exceptand their error messages handled safely. The exception fromfaulty_taskis caught insidemainand is appropriately output.
Summary
Asynchronous processing in Python uses async / await and asyncio to execute other tasks concurrently while waiting for I/O, allowing efficient processing. By leveraging concurrent execution of multiple tasks and asynchronous I/O, you can greatly improve performance. Additionally, since you can handle errors just like with regular try-except, you can safely run asynchronous code.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.