Skip to content

"Coroutines and Tasks" page does not appear to be clear about what asyncio.create_task does #96023

Closed as not planned
@ffunenga

Description

@ffunenga

In the documentation (specifically, in the "Coroutines and Tasks" page), I am having trouble understanding what happens when asyncio.create_task is called. I have read the headings Coroutines and Creating tasks, but I still don't get it.

Replicating the issue

This can be done by reading the "Coroutines and Tasks" page while trying to learn the explanations and references to the asyncio.create_task.

"Coroutines" heading

In the third point under the "three main mechanisms", the following example is provided:

async def main():
    task1 = asyncio.create_task(say_after(1, 'hello'))
    task2 = asyncio.create_task(say_after(2, 'world'))
    print(f"started at {time.strftime('%X')}")
    # Wait until both tasks are completed (should take around 2 seconds.)
    await task1
    await task2
    # (...)

My question here is: when does the say_after(2, 'world') start running? I see three options:

  1. It starts running at the line task2 = asyncio.create_task(say_after(2, 'world'))
  2. It starts running at the line await task1
  3. It starts running at the line await task2

In the third point under the "three main mechanisms", it is further explained (bold added here):

Note that expected output now shows that the snippet runs 1 second faster than before:

Why is the output "expected"? I am not finding any explanation of why this 1-sec-faster behavior is expected.

"Creating tasks" heading

In this heading, the first line of the __doc__ string for asyncio.create_task explains the following (bold added here):

Wrap the coro coroutine into a Task and schedule its execution. Return the Task object.

I don't understand what is the meaning of "schedule its execution". Does the coro get scheduled to run now or only when the program hits the next await statement?

Suggested solution

Either in the "Coroutines" heading or in the "Creating tasks" heading, inserting an explicit clarification of when the task starts running.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions