Sobes.tech
Junior — Middle

Is it possible to call synchronous operations inside an asynchronous function without errors or deadlocks?

sobes.tech AI

Answer from AI

You can call synchronous operations inside an asynchronous function in Python, but this can lead to blocking and reduced performance, especially if the synchronous operation takes a long time.

To avoid blocking, synchronous operations that may take a long time (such as input/output, database queries) are usually run in a separate thread or process using run_in_executor from the asyncio module:

import asyncio
import time

def blocking_io():
    time.sleep(3)  # simulate a long synchronous operation
    return 'result'

async def main():
    loop = asyncio.get_running_loop()
    result = await loop.run_in_executor(None, blocking_io)
    print(result)

asyncio.run(main())

Thus, the asynchronous function does not block the event loop and can handle other tasks in parallel.