Skip to content

ContextExecutor

Base classes

Name Children Inherits
ThreadPoolExecutor
concurrent.futures.thread
  • Executor

⋔ Inheritance diagram

graph TD
  3834026703["threadgroup.ContextExecutor"]
  965796427["thread.ThreadPoolExecutor"]
  407344789["_base.Executor"]
  2751680898["builtins.object"]
  965796427 --> 3834026703
  407344789 --> 965796427
  2751680898 --> 407344789

🛈 DocStrings

Bases: ThreadPoolExecutor

Thread pool executor that preserves context variables across threads.

This executor captures the current context variables when created and initializes each worker thread with this context.

Source code in src/anyenv/calling/threadgroup.py
class ContextExecutor(ThreadPoolExecutor):
    """Thread pool executor that preserves context variables across threads.

    This executor captures the current context variables when created and
    initializes each worker thread with this context.
    """

    def __init__(self, max_workers: int | None = None) -> None:
        """Initialize with the current context variables.

        Args:
            max_workers: Maximum number of worker threads to use
        """
        self.context = contextvars.copy_context()
        super().__init__(max_workers=max_workers, initializer=self._set_child_context)

    def _set_child_context(self) -> None:
        """Set the captured context variables in the worker thread."""
        for var, value in self.context.items():
            var.set(value)

__init__

__init__(max_workers: int | None = None) -> None

Initialize with the current context variables.

Parameters:

Name Type Description Default
max_workers int | None

Maximum number of worker threads to use

None
Source code in src/anyenv/calling/threadgroup.py
def __init__(self, max_workers: int | None = None) -> None:
    """Initialize with the current context variables.

    Args:
        max_workers: Maximum number of worker threads to use
    """
    self.context = contextvars.copy_context()
    super().__init__(max_workers=max_workers, initializer=self._set_child_context)

:fa-brands-github: Show source on GitHub