What is the purpose of Python’s asyncio library?
a) To provide support for asynchronous programming in Python
b) To improve the performance of multithreaded programs
c) To simplify working with dates and times in Python
d) To handle file I/O operations
Answer:
a) To provide support for asynchronous programming in Python
Explanation:
The asyncio
library in Python provides support for asynchronous programming, allowing you to write programs that can handle many tasks concurrently without being blocked by slow operations such as I/O. Asynchronous programming is particularly useful for I/O-bound and high-level structured network code.
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
# Running the asynchronous function
asyncio.run(say_hello())
In this example, say_hello()
is an asynchronous function that uses await
to pause execution for 1 second while still allowing other tasks to run concurrently.
Asynchronous programming with asyncio
allows you to write more efficient and responsive programs, particularly when dealing with network operations, file I/O, and other tasks that would otherwise block the main thread.