Safe Cancellation

async cancel_and_wait(tasks: Task[Any] | Collection[Task[Any]], /, msg: str | None = None) None[source]

Safely cancels and waits until the given task is concluded as cancelled. If the task is already terminated, it does nothing.

When the caller of this function is cancelled during waiting, cancellation is transparently raised up. Otherwise, it consumes and absorbs asyncio.CancelledError raised while awaiting the cancelled task. This is the key point of this function: it guarantees the structural safety by ensuring the caller’s control over cancellation.

If the task does not re-raise asyncio.CancelledError when awaited, it explicitly raises asyncio.InvalidStateError to warn that the task should transparently raise up injected cancellations.

See the discussion in https://github.com/python/cpython/issues/103486 for details.

Note

If you use eager task factories in Python 3.12 or later, tasks may have completed already if they do not contain any context switches (awaits) even when they are cancelled immediately after asyncio.create_task() returns. In such cases, cancel_and_wait() becomes a no-op.

Added in version 2.0.