Task Context
- 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.WeakSetto keep track of child tasks for a long-running server application with TaskContext.If
exception_handleris not set (the default behavior), it will runloop.call_exception_handler()with the context argument consisting of themessage,task(the child task that raised the exception), andexception(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 tocreate_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.