Skip to content

Confusing asyncio.create_task documentation about task lifetime #117379

Closed as not planned
@sklibanov312

Description

@sklibanov312

Documentation

The document for asyncio.create_task - https://docs.python.org/3.10/library/asyncio-task.html#asyncio.create_task - states very plainly:

Important Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn’t referenced elsewhere may get garbage collected at any time, even before it’s done. For reliable “fire-and-forget” background tasks, gather them in a collection:

Is there a program that proves this behavior to be true? Here's my attempt at showing this behavior:

import asyncio
import gc

async def forever():
    while True:
        print('forever')
        await asyncio.sleep(1)
		
async def forever_and_one_day():
    # From https://docs.python.org/3.10/library/asyncio-task.html#asyncio.create_task :
    # "Save a reference to the result of this function, to avoid a task disappearing mid-execution."
    # So ... shouldn't it disappear? But it doesn't? When will this hurt?
    asyncio.create_task(forever())
    while True:
        print('and a day')
        await asyncio.sleep(1)
        gc.collect()
        

asyncio.run(forever_and_one_day())

However, I ran this example in Python 3.9, 3.10, 3.11 and 3.12 and it continues printing 'forever' and 'and a day' for as long as I care to let it run. According to my interpretation of the docs, it ought to stop printing 'forever', because the result of create_task is not saved anywhere. But it doesn't stop, it just continues.

So what does this documentation actually mean? How do we change this program to exhibit the documented behavior of tasks disappearing mid-execution?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions