Why does awaiting the second task invoke the first task?

Viewed 31

This Python 3.10 code

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    t1 = asyncio.create_task(say_after(1, 'task 1'))
    t2 = asyncio.create_task(say_after(2, 'task 2'))

    print(f'Start at {time.strftime("%X")}')

    await t2

    print(f'End at {time.strftime("%X")}')

asyncio.run(main(), debug=True)

outputs this:

Start at 03:32:50
task 1
task 2
End at 03:32:52

I didn't await t1 but it still runs.

Code is taken from here and modified.

1 Answers

create_task schedules a task to be executed by the event loop. It will be executed in the background if the event loop runs long enough, whether you await it or not.

Awaiting t2 just happens to let the event loop run long enough to finish t1, too.

If you swap the sleep durations, you should not see the output from t1, because the main program finishes before it is done.

Related