Junior — Middle
How can synchronous code be transformed into asynchronous code to improve system performance or responsiveness?
sobes.tech AI
Answer from AI
To convert synchronous code to asynchronous in Python, you need to use the capabilities of the asyncio module and the keywords async and await. This allows the program to not block execution while waiting for I/O operations, improving responsiveness and performance.
Main steps:
- Define functions as asynchronous using
async def. - Use
awaitat points where waiting occurs (e.g., network requests, file reading) to call asynchronous operations. - Run asynchronous code through the event loop
asyncio.run().
Example:
import asyncio
async def fetch_data():
print("Starting download")
await asyncio.sleep(2) # simulate asynchronous operation
print("Download complete")
async def main():
await fetch_data()
asyncio.run(main())
This approach allows other tasks to run during waiting, increasing overall program efficiency.