[Python] Why in python would blocking code delay a non-blocking sleep timer?

Discussão em 'Python' iniciado por Stack, Maio 19, 2025.

  1. Stack

    Stack Membro Participativo

    In python, if I run the following code:

    import asyncio
    import time

    from datetime import datetime

    async def delay(n: int, id: str):
    await asyncio.sleep(n)
    print("I am:", id, datetime.now())
    return id


    async def main():
    second = delay(1, "second")
    first = delay(1, "First")
    task = asyncio.create_task(second)
    time.sleep(2) # Removable, this is here to show "second" is being delayed until after first resolves
    await first



    asyncio.run(main())


    My expectation is if we consider T+0 the start time of the application. The create_task would start first and a timer (at roughly T+0) would be set to resolve at T+1. The sleep timer would then start and block everything until T+2. At this point, this seems to diverge from my expectations. My expectation is that the first coroutine is then run and I would expect at that time the await asyncio.sleep from the second coroutine to be able to take control and complete. This does not appear to be what happens though. It seems that first resolves at T+3 after which first then resolves as well at T+3. Why is "second" delayed until T+3 (instead of resolving at T+2) and why does it not resolve immediately when the sleep call is made in "first" coroutine?

    Note: I am aware that time.sleep is preventing second task from continuing. The question is why is first completed prior to second even though second started running and called asyncio.sleep prior to first being started and calling asyncio.sleep later? Presumably, the second sleep call has already waited for 1 second prior to first even calling await asyncio.sleep.

    Continue reading...

Compartilhe esta Página