Junior — Middle
How can you write a function that executes asynchronously, i.e., does not block the main execution thread?
sobes.tech AI
Answer from AI
In Python, the keyword async def is used to write asynchronous functions. Such a function returns a coroutine, which can be executed using await or run in the asyncio event loop. This allows not to block the main thread, as the execution of the function is suspended at await points, giving other tasks the opportunity to run concurrently.
Example of an asynchronous function:
import asyncio
async def async_function():
print("Start")
await asyncio.sleep(1) # simulate an asynchronous operation
print("End")
async def main():
await async_function()
asyncio.run(main())
In this example, asyncio.sleep(1) does not block the thread but suspends execution for 1 second, allowing other tasks to run.