Sobes.tech
Junior — Middle

Can you explain the concept of asynchronous programming and how to implement it in Python using async/await?

sobes.tech AI

Answer from AI

Asynchronous programming allows tasks to be executed without blocking the main thread, which is especially useful for I/O operations or network requests.

In Python, this is achieved using the keywords async and await:

  • async def declares an asynchronous function (coroutine).
  • await suspends the coroutine until the asynchronous operation completes.

Example:

import asyncio

async def say_hello():
    print("Hello")
    await asyncio.sleep(1)  # simulates an async operation
    print("World")

async def main():
    await say_hello()

asyncio.run(main())

Here, asyncio.sleep is an async delay that does not block the thread.