Skip to content

ThreadGroup

Base classes

Name Children Inherits
Generic
typing
Abstract base class for generic types.

⋔ Inheritance diagram

graph TD
  2492307227["threadgroup.ThreadGroup"]
  3481597255["typing.Generic"]
  2751680898["builtins.object"]
  3481597255 --> 2492307227
  2751680898 --> 3481597255

🛈 DocStrings

Class that executes functions in parallel, with TaskGroup-like API.

Source code in src/anyenv/calling/threadgroup.py
class ThreadGroup[R = Any]:
    """Class that executes functions in parallel, with TaskGroup-like API."""

    def __init__(
        self,
        max_workers: int | None = None,
        raise_exceptions: bool = True,
        preserve_context: bool = False,
    ) -> None:
        """Thread task group that executes functions in parallel.

        Supports both sync and async context managers.

        Args:
            max_workers: Maximum number of worker threads
            raise_exceptions: If True, raises exceptions from tasks
            preserve_context: If True, preserves context variables across threads
        """
        self.max_workers = max_workers
        self.raise_exceptions = raise_exceptions
        self.preserve_context = preserve_context

        if preserve_context:
            self.executor: ThreadPoolExecutor = ContextExecutor(max_workers=self.max_workers)
        else:
            self.executor = ThreadPoolExecutor(max_workers=self.max_workers)

        self.futures: list[concurrent.futures.Future[R]] = []
        self._results: list[R] = []
        self._exceptions: list[Exception] = []
        self._logger = logging.getLogger(self.__class__.__name__)

    def spawn(
        self, func: Callable[..., R], *args: Any, **kwargs: Any
    ) -> concurrent.futures.Future[R]:
        """Submit a task immediately to the executor.

        Args:
            func: The function to execute
            *args: Positional arguments to pass to the function
            **kwargs: Keyword arguments to pass to the function

        Returns:
            Future object representing the execution of the function
        """
        future = self.executor.submit(func, *args, **kwargs)
        self.futures.append(future)
        return future

    def __enter__(self) -> ThreadGroup[R]:
        """Enter the context manager."""
        return self

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Exit the context manager: wait for all tasks and shut the executor down.

        Results are collected in spawn order. On the first failure (with
        ``raise_exceptions``) tasks that haven't started are cancelled, the running
        ones are waited for, then the first failure in spawn order is raised.
        """
        futures, self.futures = self.futures, []
        try:
            done, _ = concurrent.futures.wait(
                futures, return_when=concurrent.futures.FIRST_EXCEPTION
            )
            if self.raise_exceptions and any(
                not f.cancelled() and f.exception() is not None for f in done
            ):
                for future in futures:
                    future.cancel()
            concurrent.futures.wait(futures)
        finally:
            self.executor.shutdown(wait=True)

        first_error: Exception | None = None
        for future in futures:
            if future.cancelled():
                continue
            try:
                self._results.append(future.result())
            except Exception as e:
                self._exceptions.append(e)
                self._logger.exception("Task error")
                first_error = first_error or e
        if first_error is not None and self.raise_exceptions:
            raise first_error

    async def __aenter__(self) -> ThreadGroup[R]:
        """Enter the async context manager."""
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Exit the async context manager, waiting without blocking the event loop."""
        await asyncio.to_thread(self.__exit__, exc_type, exc_val, exc_tb)

    def shutdown(self) -> None:
        """Shutdown the executor when done with the ThreadGroup."""
        self.executor.shutdown()

    @property
    def results(self) -> list[R]:
        """List of results from completed tasks."""
        return self._results

    @property
    def exceptions(self) -> list[Exception]:
        """List of exceptions raised by tasks."""
        return self._exceptions

exceptions property

exceptions: list[Exception]

List of exceptions raised by tasks.

results property

results: list[R]

List of results from completed tasks.

__aenter__ async

__aenter__() -> ThreadGroup[R]

Enter the async context manager.

Source code in src/anyenv/calling/threadgroup.py
async def __aenter__(self) -> ThreadGroup[R]:
    """Enter the async context manager."""
    return self

__aexit__ async

__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Exit the async context manager, waiting without blocking the event loop.

Source code in src/anyenv/calling/threadgroup.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Exit the async context manager, waiting without blocking the event loop."""
    await asyncio.to_thread(self.__exit__, exc_type, exc_val, exc_tb)

__enter__

__enter__() -> ThreadGroup[R]

Enter the context manager.

Source code in src/anyenv/calling/threadgroup.py
def __enter__(self) -> ThreadGroup[R]:
    """Enter the context manager."""
    return self

__exit__

__exit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Exit the context manager: wait for all tasks and shut the executor down.

Results are collected in spawn order. On the first failure (with raise_exceptions) tasks that haven't started are cancelled, the running ones are waited for, then the first failure in spawn order is raised.

Source code in src/anyenv/calling/threadgroup.py
def __exit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Exit the context manager: wait for all tasks and shut the executor down.

    Results are collected in spawn order. On the first failure (with
    ``raise_exceptions``) tasks that haven't started are cancelled, the running
    ones are waited for, then the first failure in spawn order is raised.
    """
    futures, self.futures = self.futures, []
    try:
        done, _ = concurrent.futures.wait(
            futures, return_when=concurrent.futures.FIRST_EXCEPTION
        )
        if self.raise_exceptions and any(
            not f.cancelled() and f.exception() is not None for f in done
        ):
            for future in futures:
                future.cancel()
        concurrent.futures.wait(futures)
    finally:
        self.executor.shutdown(wait=True)

    first_error: Exception | None = None
    for future in futures:
        if future.cancelled():
            continue
        try:
            self._results.append(future.result())
        except Exception as e:
            self._exceptions.append(e)
            self._logger.exception("Task error")
            first_error = first_error or e
    if first_error is not None and self.raise_exceptions:
        raise first_error

__init__

__init__(
    max_workers: int | None = None, raise_exceptions: bool = True, preserve_context: bool = False
) -> None

Thread task group that executes functions in parallel.

Supports both sync and async context managers.

Parameters:

Name Type Description Default
max_workers int | None

Maximum number of worker threads

None
raise_exceptions bool

If True, raises exceptions from tasks

True
preserve_context bool

If True, preserves context variables across threads

False
Source code in src/anyenv/calling/threadgroup.py
def __init__(
    self,
    max_workers: int | None = None,
    raise_exceptions: bool = True,
    preserve_context: bool = False,
) -> None:
    """Thread task group that executes functions in parallel.

    Supports both sync and async context managers.

    Args:
        max_workers: Maximum number of worker threads
        raise_exceptions: If True, raises exceptions from tasks
        preserve_context: If True, preserves context variables across threads
    """
    self.max_workers = max_workers
    self.raise_exceptions = raise_exceptions
    self.preserve_context = preserve_context

    if preserve_context:
        self.executor: ThreadPoolExecutor = ContextExecutor(max_workers=self.max_workers)
    else:
        self.executor = ThreadPoolExecutor(max_workers=self.max_workers)

    self.futures: list[concurrent.futures.Future[R]] = []
    self._results: list[R] = []
    self._exceptions: list[Exception] = []
    self._logger = logging.getLogger(self.__class__.__name__)

shutdown

shutdown() -> None

Shutdown the executor when done with the ThreadGroup.

Source code in src/anyenv/calling/threadgroup.py
def shutdown(self) -> None:
    """Shutdown the executor when done with the ThreadGroup."""
    self.executor.shutdown()

spawn

spawn(func: Callable[..., R], *args: Any, **kwargs: Any) -> Future[R]

Submit a task immediately to the executor.

Parameters:

Name Type Description Default
func Callable[..., R]

The function to execute

required
*args Any

Positional arguments to pass to the function

()
**kwargs Any

Keyword arguments to pass to the function

{}

Returns:

Type Description
Future[R]

Future object representing the execution of the function

Source code in src/anyenv/calling/threadgroup.py
def spawn(
    self, func: Callable[..., R], *args: Any, **kwargs: Any
) -> concurrent.futures.Future[R]:
    """Submit a task immediately to the executor.

    Args:
        func: The function to execute
        *args: Positional arguments to pass to the function
        **kwargs: Keyword arguments to pass to the function

    Returns:
        Future object representing the execution of the function
    """
    future = self.executor.submit(func, *args, **kwargs)
    self.futures.append(future)
    return future

:fa-brands-github: Show source on GitHub