Monday, February 3, 2025

Top 10 Python asyncio Interview Questions and Answers



Python's `asyncio` library is a powerful tool for writing concurrent code using the `async`/`await` syntax. Here are some commonly asked interview questions on `asyncio` along with their answers to help you prepare:


1. Write an asynchronous function using `async def` that prints "Hello, World!" after a 1-second delay.

   import asyncio

   async def greet():
       await asyncio.sleep(1)
       print("Hello, World!")

   asyncio.run(greet())

 


2. Create a coroutine that fetches data from a URL using `aiohttp` and prints the response status.


   import aiohttp
   import asyncio

   async def fetch_url(url):
       async with aiohttp.ClientSession() as session:
           async with session.get(url) as response:
               print(response.status)

   asyncio.run(fetch_url("https://www.example.com"))

3. Write a program that uses `asyncio.gather` to run three asynchronous functions concurrently, each with different sleep durations, and print their results.

  
   import asyncio

   async def task1():
       await asyncio.sleep(1)
       return "task1 completed"

   async def task2():
       await asyncio.sleep(2)
       return "task2 completed"

   async def task3():
       await asyncio.sleep(3)
       return "task3 completed"

   async def main():
       results = await asyncio.gather(task1(), task2(), task3())
       print(results)

   asyncio.run(main())
  

4. Implement a coroutine that reads from a file asynchronously using `aiofiles`. Print the contents of the file.

  
   import aiofiles
   import asyncio

   async def read_file(file_path):
       async with aiofiles.open(file_path, mode='r') as file:
           contents = await file.read()
           print(contents)

   asyncio.run(read_file('example.txt'))
  

5. Create an asynchronous context manager using `async with` that handles a mock resource and prints messages when acquiring and releasing the resource.

  
   import asyncio

   class MockResource:
       async def __aenter__(self):
           print("Acquiring resource")
           return self

       async def __aexit__(self, exc_type, exc_value, traceback):
           print("Releasing resource")

   async def use_resource():
       async with MockResource():
           print("Using resource")

   asyncio.run(use_resource())
  

6. Write a coroutine that catches exceptions during the execution of an asynchronous function and prints the error message.

  
   import asyncio

   async def error_prone_task():
       raise ValueError("An error occurred")

   async def main():
       try:
           await error_prone_task()
       except ValueError as e:
           print(f"Caught an exception: {e}")

   asyncio.run(main())
  

7. Develop a coroutine that uses `asyncio.sleep()` to simulate a delay and then prints a message, demonstrating the difference between `asyncio.sleep()` and `time.sleep()`.

  
   import asyncio
   import time

   async def async_sleep_example():
       await asyncio.sleep(1)
       print("Non-blocking sleep complete")

   def blocking_sleep_example():
       time.sleep(1)
       print("Blocking sleep complete")

   asyncio.run(async_sleep_example())
   blocking_sleep_example()
  

8. Create a coroutine that runs multiple asynchronous tasks using `asyncio.create_task` and prints their results.

  
   import asyncio

   async def task1():
       await asyncio.sleep(1)
       return "task1 result"

   async def task2():
       await asyncio.sleep(2)
       return "task2 result"

   async def main():
       t1 = asyncio.create_task(task1())
       t2 = asyncio.create_task(task2())
       results = await asyncio.gather(t1, t2)
       print(results)

   asyncio.run(main())
  

9. Write a coroutine that demonstrates how to cancel an asynchronous task.

  
   import asyncio

   async def long_running_task():
       try:
           await asyncio.sleep(10)
       except asyncio.CancelledError:
           print("Task was cancelled")

   async def main():
       task = asyncio.create_task(long_running_task())
       await asyncio.sleep(1)
       task.cancel()
       await task

   asyncio.run(main())
  

10. Implement a simple web server using `aiohttp` that responds with "Hello, World!" to any GET request.

  
   import aiohttp
   import aiohttp.web
   import asyncio

   async def handle(request):
       return aiohttp.web.Response(text="Hello, World!")

   app = aiohttp.web.Application()
   app.router.add_get('/', handle)

   aiohttp.web.run_app(app)
  

---
By the way, some intern position ask easier question such as these:


1. What is `asyncio` in Python?
   `asyncio` is a library to write concurrent code using the `async`/`await` syntax. It is used to handle asynchronous operations and is included in Python's standard library from version 3.4 onwards.

2. What is an event loop in `asyncio`?
   An event loop is the core of every `asyncio` application. It runs in a thread (usually the main thread) and schedules and executes asynchronous tasks, handling all the asynchronous operations.

3. How do you define an asynchronous function in Python?
   An asynchronous function is defined using the `async def` syntax. For example:
  
   async def my_async_function():
       pass
  

4. What are `await` and `async` keywords used for?
   - `async`: Used to define an asynchronous function.
   - `await`: Used to pause the execution of an asynchronous function until the awaited task completes, freeing up the event loop for other tasks.

5. How do you run an asynchronous function using `asyncio`?
   You can run an asynchronous function using the `asyncio.run()` function or by running it within an event loop. For example:
  
   import asyncio

   async def main():
       print("Hello, World!")

   asyncio.run(main())
  

6. What is a coroutine in Python `asyncio`?
   A coroutine is a function that can be paused and resumed, allowing other tasks to run during the pause. Coroutines are defined with the `async` keyword and are the building blocks of `asyncio`.

7. How do you handle exceptions in `asyncio` coroutines?
   Exceptions in `asyncio` coroutines can be handled using `try` and `except` blocks within the asynchronous function:
  
   async def example():
       try:
           result = await some_coroutine()
       except Exception as e:
           print(f"An error occurred: {e}")
  

8. What is `asyncio.gather` and how is it used?
   `asyncio.gather` is a function that runs multiple asynchronous tasks concurrently and waits for all of them to complete. For example:

   import asyncio

   async def task1():
       await asyncio.sleep(1)
       return "task1 completed"

   async def task2():
       await asyncio.sleep(2)
       return "task2 completed"

   async def main():
       results = await asyncio.gather(task1(), task2())
       print(results)

   asyncio.run(main())


9. What are the differences between `asyncio.sleep()` and `time.sleep()`?
   - `asyncio.sleep()`: Non-blocking, allows the event loop to run other tasks while sleeping.
   - `time.sleep()`: Blocking, pauses the entire thread, preventing other tasks from running.


10. How do you use `async with` in `asyncio`?
    `async with` is used with asynchronous context managers. It ensures that the resource is properly acquired and released. For example:
 

 

    import aiohttp

    async def fetch(url):
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                return await response.text()