Junior — Middle
Can you explain what asynchronous code execution in Python means and how it works?
sobes.tech AI
Answer from AI
Asynchronous code execution in Python allows running operations that may take time (such as network requests or file reading) without blocking the main thread of the program.
This is achieved using the keywords async and await. Functions declared with async def are called coroutines and can suspend their execution at await points, allowing other tasks to run concurrently.
Example:
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1) # simulate delay
print("Goodbye")
async def main():
await asyncio.gather(say_hello(), say_hello())
asyncio.run(main())
In this example, two coroutines run simultaneously, and the program does not block during the sleep wait. Asynchronous programming is useful for improving performance when working with I/O operations.