Junior — Middle
Can you explain what asynchronous task execution in Python is and how it works?
sobes.tech AI
Answer from AI
Asynchronous execution of tasks in Python allows running operations that may take time (for example, input/output) without blocking the main thread of execution. This is achieved using the keywords async and await, as well as the event loop.
The main idea is that a task (coroutine) releases control while waiting for a result, allowing other tasks to run. This increases efficiency, especially when working with network requests or files.
Example of an asynchronous function:
import asyncio
async def say_hello():
print('Hello')
await asyncio.sleep(1) # simulate delay
print('World')
async def main():
await say_hello()
asyncio.run(main())
Here, asyncio.sleep is a non-blocking delay that allows other tasks to execute during this time.