Skip to content

Cancelling a task A awaiting another task B cancels task B #141186

@qris

Description

@qris

Documentation

This is the issue described in #138717, which was closed as "not planned" because (I think) no acceptable resolution was proposed.

I think that issue might not have been raised if it was clearly documented that it would happen.

It also had to be explicitly explained in this comment:

Cancelling any future propagates the error down the chain of await, cancelling each future

This code is a trivial example:

async def test_sub_cancellation():
    """Does cancelling a coro waiting on a Task also cancel that Task?"""
    async def coro1():
        await asyncio.sleep(2)
    task1 = asyncio.create_task(coro1())
    async def coro2():
        await task1
    with pytest.raises(asyncio.TimeoutError):
        await asyncio.wait_for(coro2(), 1)
    assert task1.cancelled()  # implicitly when coro2 was cancelled?

The docs say (way, way down) that:

If a coroutine is awaiting on a Future object during cancellation, the Future object will be cancelled.

This does actually apply because Tasks are a subset of Futures, but that doesn't seem to be documented (so I didn't know until I looked at the code for Task). I am using this behaviour, not objecting to it, but I'm worried that being undocumented it might change without warning.

It might be as simple as changing that text to:

If a coroutine is awaiting on a Future or Task object during cancellation, the awaited object will be cancelled.

And/or stating explicitly that Tasks are actually Futures.

Also I think that a coroutine cannot actually be cancelled (only Tasks and Futures can be), so this language is maybe not completely clear.

It might also be worth repeating that under "Task cancellation" higher up, in this para:

Tasks can easily and safely be cancelled. When a task is cancelled, asyncio.CancelledError will be raised in the task at the next opportunity.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Status

    Done

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions