Task Context

class ErrorArg[source]
exception: BaseException
message: str
task: Task[Any]
class TaskContext(*, exception_handler: Callable[[ErrorArg], None] | LoopExceptionHandler | None = LoopExceptionHandler.TOKEN, context: Context | None = None)[source]

TaskContext keeps the references to the child tasks during its lifetime, so that they can be terminated safely when shutdown is explicitly requested.

This is the loosest form of child task managers among TaskScope, TaskGroup, and Supervisor, as it does not enforce structured concurrency but just provides a reference set to child tasks.

You may replace existing patterns using weakref.WeakSet to keep track of child tasks for a long-running server application with TaskContext.

If exception_handler is not set (the default behavior), it will run loop.call_exception_handler() with the context argument consisting of the message, task (the child task that raised the exception), and exception (the exception object) fields.

If it is set None, it will silently ignore the exception.

If it is set as a callable function, it will invoke the specified callback function using the context argument same to that used when calling loop.call_exception_handler().

If you provide context, it will be passed to create_task() by default.

Note

Unlike TaskScope, TaskContext does not update the callgraph introduced in Python 3.14 as it does not implement completion-based waiting semantics but just grouped cancellation when explicitly requested.

Added in version 2.0.

async aclose() None[source]

Triggers cancellation and waits for completion.

create_task(coro: Coroutine[Any, Any, T], *, name: str | None = None, context: Context | None = None, **kwargs: Any) Task[T][source]

Create a new task in this scope and return it. Similar to asyncio.create_task().