Sobes.tech
Junior — Middle

What will happen if a blocking delay time.sleep() is applied in an asynchronous function?

sobes.tech AI

Answer from AI

If you use a blocking delay time.sleep() in an asynchronous Python function, the entire program execution will be paused during the sleep time, blocking the current thread. This defeats the advantages of asynchrony, as other tasks in the event loop cannot run in parallel.

Instead of time.sleep(), you should use await asyncio.sleep() in asynchronous code, which does not block the event loop and allows other coroutines to run during the wait.

Example:

import asyncio
import time

async def wrong_sleep():
    print('Start')
    time.sleep(2)  # blocks the entire event loop
    print('End')

async def correct_sleep():
    print('Start')
    await asyncio.sleep(2)  # does not block the event loop
    print('End')

asyncio.run(correct_sleep())