[Python] Python async sleep question ordering of execution

Discussão em 'Python' iniciado por Stack, Outubro 24, 2024.

  1. Stack

    Stack Membro Participativo

    Hello I have a quesiton while I'm working through some tutorial on asyncio as given below:

    import asyncio
    async def task_coroutine():
    print('start executing task')
    await asyncio.sleep(1.0)
    print('done waiting in task')
    raise Exception('error in task')
    return 99

    async def main():
    print('main started')
    task = asyncio.create_task(task_coroutine())
    await asyncio.sleep(1.1)
    print('done waiting in main')
    try:
    value = task.result()
    except Exception as e:
    print(e)
    print('end of main')
    asyncio.run(main())



    as I expected, the result is

    main started
    start executing task
    done waiting in task
    done waiting in main
    error in task
    end of main


    because when the task suspend, the main is still sleeping and it switches back to task to throw.

    I have been playing around a bit by changing the sleep time of main to 0.1 (1.1 before) and the result is also as I expected

    main started
    start executing task
    done waiting in main
    Result is not set.
    end of main


    since the main trying to collect result of task before it's done so it throws "Result is not set"

    However, when I set the sleep time of main to 1.0000000001, it gives:

    main started
    start executing task
    done waiting in main
    Result is not set.
    end of main
    done waiting in task

    Task exception was never retrieved
    future: <Task finished name='Task-2' coro=<task_coroutine() done, defined at /Users/user/Library/Application Support/JetBrains/PyCharm2024.1/scratches/scratch.py:3> exception=Exception('error in task')>
    Traceback (most recent call last):
    File "/Users/charlielao/Library/Application Support/JetBrains/PyCharm2024.1/scratches/scratch.py", line 7, in task_coroutine
    raise Exception('error in task')
    Exception: error in task


    I don't quite understand why it prints "done waiting in task" at the end after main finishes where it didn't in the 0.1 case, why is there explicit error in this case, what was the exact ordering of events?

    Continue reading...

Compartilhe esta Página