[Python] What does asyncio.create_task() do?

Discussão em 'Python' iniciado por Stack, Abril 25, 2025.

  1. Stack

    Stack Membro Participativo

    What does asyncio.create_task() do? A bit of code that confuses me is this:

    import asyncio

    async def counter_loop(x, n):
    for i in range(1, n + 1):
    print(f"Counter {x}: {i}")
    await asyncio.sleep(0.5)
    return f"Finished {x} in {n}"

    async def main():
    slow_task = asyncio.create_task(counter_loop("Slow", 4))
    fast_coro = counter_loop("Fast", 2)

    print("Awaiting Fast")
    fast_val = await fast_coro
    print("Finished Fast")

    print("Awaiting Slow")
    slow_val = await slow_task
    print("Finished Slow")

    print(f"{fast_val}, {slow_val}")

    asyncio.run(main())


    This outputs:

    001 | Awaiting Fast
    002 | Counter Fast: 1
    003 | Counter Slow: 1
    004 | Counter Fast: 2
    005 | Counter Slow: 2
    006 | Finished Fast
    007 | Awaiting Slow
    008 | Counter Slow: 3
    009 | Counter Slow: 4
    010 | Finished Slow
    011 | Finished Fast in 2, Finished Slow in 4


    I don't understand quite how this is working.

    1. Shouldn't the slow_task not be able to run until the completion of the fast_coro because it was never used in an asyncio.gather() method?
    2. Why do we have to await slow_task?
    3. Why is "Awaiting Slow" printed after the coroutine appears to have started?
    4. What really is a task? I know that what gather is doing is scheduling a task. And create_task supposedly creates a task.

    Continue reading...

Compartilhe esta Página