Skip to content

async_run

Class info

🛈 DocStrings

Utilities for running async code in a synchronous context.

as_generated async

as_generated(
    iterables: Iterable[AsyncIterable[T]], *, return_exceptions: bool = False
) -> AsyncGenerator[T]

Yield results from one or more async iterables, in the order they are produced.

Like :func:as_completed, but for async iterators or generators instead of futures. Creates a separate task to drain each iterable, and a single queue for results.

If return_exceptions is False, then any exception will be raised, and pending iterables and tasks will be cancelled, and async generators will be closed. If return_exceptions is True, any exceptions will be yielded as results, and execution will continue until all iterables have been fully consumed. Cancelling the consumer cancels the sources and propagates.

Example::

async def generator(x):
    for i in range(x):
        yield i

gen1 = generator(10)
gen2 = generator(12)

async for value in as_generated([gen1, gen2]):
    ...  # intermixed values yielded from gen1 and gen2
Source code in src/anyenv/async_run.py
async def as_generated[T](
    iterables: Iterable[AsyncIterable[T]],
    *,
    return_exceptions: bool = False,
) -> AsyncGenerator[T]:
    """Yield results from one or more async iterables, in the order they are produced.

    Like :func:`as_completed`, but for async iterators or generators instead of futures.
    Creates a separate task to drain each iterable, and a single queue for results.

    If ``return_exceptions`` is ``False``, then any exception will be raised, and
    pending iterables and tasks will be cancelled, and async generators will be closed.
    If ``return_exceptions`` is ``True``, any exceptions will be yielded as results,
    and execution will continue until all iterables have been fully consumed.
    Cancelling the consumer cancels the sources and propagates.

    Example::

        async def generator(x):
            for i in range(x):
                yield i

        gen1 = generator(10)
        gen2 = generator(12)

        async for value in as_generated([gen1, gen2]):
            ...  # intermixed values yielded from gen1 and gen2
    """
    # (kind, payload): values, a source's error and its end share one queue, in order.
    queue: asyncio.Queue[tuple[int, Any]] = asyncio.Queue()

    async def tailer(iterable: AsyncIterable[T]) -> None:
        try:
            async for item in iterable:
                queue.put_nowait((_ITEM, item))
        except asyncio.CancelledError:
            if isinstance(iterable, AsyncGenerator):
                await iterable.aclose()
            raise
        except Exception as e:  # noqa: BLE001
            queue.put_nowait((_ERROR, e))
        finally:
            queue.put_nowait((_DONE, None))

    tasks = [asyncio.ensure_future(tailer(i)) for i in iterables]
    remaining = len(tasks)
    try:
        while remaining:
            kind, payload = await queue.get()
            if kind == _DONE:
                remaining -= 1
            elif kind == _ERROR and not return_exceptions:
                raise payload
            else:
                yield payload
    finally:
        for task in tasks:
            task.cancel()
        if tasks:
            # wait() neither raises the tasks' cancellation nor swallows our own.
            await asyncio.wait(tasks)

call_and_gather async

call_and_gather(
    callables: Sequence[Callable[..., Awaitable[T]]],
    args: tuple[Any, ...] | Sequence[tuple[Any, ...]],
    kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None,
    return_exceptions: Literal[True],
    limit: int | None = None,
) -> Sequence[T | BaseException]
call_and_gather(
    callables: Sequence[Callable[..., Awaitable[T]]],
    args: tuple[Any, ...] | Sequence[tuple[Any, ...]] = (),
    kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None = None,
    *,
    return_exceptions: Literal[True],
    limit: int | None = None,
) -> Sequence[T | BaseException]
call_and_gather(
    callables: Sequence[Callable[..., Awaitable[T]]],
    args: tuple[Any, ...] | Sequence[tuple[Any, ...]] = (),
    kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None = None,
    return_exceptions: Literal[False] = False,
    limit: int | None = None,
) -> Sequence[T]
call_and_gather(
    callables: Sequence[Callable[..., Awaitable[T]]],
    args: tuple[Any, ...] | Sequence[tuple[Any, ...]] = (),
    kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None = None,
    return_exceptions: bool = False,
    limit: int | None = None,
) -> Sequence[T | BaseException]

Call multiple callables and gather their results concurrently.

This is a helper for the common pattern of calling multiple handlers/functions and gathering their results concurrently. Supports two modes:

  1. Broadcast mode: Same args/kwargs for all callables
  2. Per-callable mode: Different args/kwargs for each callable

Uses aioitertools.asyncio.gather if available for limit support, falls back to the local gather implementation otherwise.

Parameters:

Name Type Description Default
callables Sequence[Callable[..., Awaitable[T]]]

Sequence of callable objects that return awaitables

required
args tuple[Any, ...] | Sequence[tuple[Any, ...]]

Single tuple (broadcast) or sequence of tuples (per-callable)

()
kwargs dict[str, Any] | Sequence[dict[str, Any]] | None

Single dict (broadcast) or sequence of dicts (per-callable)

None
return_exceptions bool

If True, exceptions are returned instead of raised

False
limit int | None

Maximum concurrent tasks (None for unlimited, only with aioitertools)

None

Returns:

Type Description
Sequence[T | BaseException]

A sequence of results in the same order as the input callables

Source code in src/anyenv/async_run.py
async def call_and_gather[T](
    callables: Sequence[Callable[..., Awaitable[T]]],
    args: tuple[Any, ...] | Sequence[tuple[Any, ...]] = (),
    kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None = None,
    return_exceptions: bool = False,
    limit: int | None = None,
) -> Sequence[T | BaseException]:
    """Call multiple callables and gather their results concurrently.

    This is a helper for the common pattern of calling multiple handlers/functions
    and gathering their results concurrently. Supports two modes:

    1. Broadcast mode: Same args/kwargs for all callables
    2. Per-callable mode: Different args/kwargs for each callable

    Uses aioitertools.asyncio.gather if available for limit support,
    falls back to the local gather implementation otherwise.

    Args:
        callables: Sequence of callable objects that return awaitables
        args: Single tuple (broadcast) or sequence of tuples (per-callable)
        kwargs: Single dict (broadcast) or sequence of dicts (per-callable)
        return_exceptions: If True, exceptions are returned instead of raised
        limit: Maximum concurrent tasks (None for unlimited, only with aioitertools)

    Returns:
        A sequence of results in the same order as the input callables
    """
    from aioitertools.asyncio import gather as aioitertools_gather

    if kwargs is None:
        kwargs = {}

    # Detect mode based on types
    args_is_broadcast = isinstance(args, tuple)
    kwargs_is_broadcast = isinstance(kwargs, dict)

    # Validate consistent mode
    if args_is_broadcast and not kwargs_is_broadcast:
        msg = "Mixed modes: args is broadcast (tuple) but kwargs is per-callable (sequence)"
        raise ValueError(msg)
    if not args_is_broadcast and kwargs_is_broadcast:
        msg = "Mixed modes: args is per-callable (sequence) but kwargs is broadcast (dict)"
        raise ValueError(msg)

    if args_is_broadcast and kwargs_is_broadcast:
        # Broadcast mode: same args/kwargs for all

        args_tuple = cast(tuple[Any, ...], args)
        kwargs_dict = cast(dict[str, Any], kwargs)
        coros = [callable_obj(*args_tuple, **kwargs_dict) for callable_obj in callables]
    else:
        # Per-callable mode: different args/kwargs for each

        args_seq = cast(Sequence[tuple[Any, ...]], args)
        kwargs_seq = cast(Sequence[dict[str, Any]], kwargs)

        if not (len(args_seq) == len(kwargs_seq) == len(callables)):
            msg = (
                f"Length mismatch: callables({len(callables)}), "
                f"args({len(args_seq)}), kwargs({len(kwargs_seq)}) must all be equal"
            )
            raise ValueError(msg)

        coros = [
            callable_obj(*call_args, **call_kwargs)
            for callable_obj, call_args, call_kwargs in zip(
                callables,
                args_seq,
                kwargs_seq,
                strict=True,
            )
        ]

    if limit is not None:
        # Use aioitertools.asyncio.gather with limit support
        return await aioitertools_gather(*coros, return_exceptions=return_exceptions, limit=limit)
    # Fall back to our local gather implementation
    if return_exceptions:
        return await gather(*coros, return_exceptions=True)
    return await gather(*coros, return_exceptions=False)

execute async

execute(
    func: Callable[..., T | Awaitable[T]], *args: Any, use_thread: bool = False, **kwargs: Any
) -> T

Execute callable, handling both sync and async cases.

Source code in src/anyenv/async_run.py
async def execute[T](
    func: Callable[..., T | Awaitable[T]],
    *args: Any,
    use_thread: bool = False,
    **kwargs: Any,
) -> T:
    """Execute callable, handling both sync and async cases."""
    if inspect.iscoroutinefunction(func):
        return await func(*args, **kwargs)  # type: ignore[no-any-return]

    if use_thread:
        return await asyncio.to_thread(func, *args, **kwargs)  # type: ignore

    return func(*args, **kwargs)  # type: ignore

gather async

gather(
    *coros_or_futures: Awaitable[T], return_exceptions: Literal[True]
) -> Sequence[T | Exception]
gather(
    *coros_or_futures: Awaitable[T], return_exceptions: Literal[False] = False
) -> Sequence[T]
gather(
    *coros_or_futures: Awaitable[T], return_exceptions: bool = False
) -> Sequence[T | Exception]

Run awaitables concurrently using anyio's task groups.

Like asyncio.gather, a failure raises the failing awaitable's own exception (the first one, if several fail), not an ExceptionGroup; the others are cancelled. Cancellation is never returned as a result.

Parameters:

Name Type Description Default
*coros_or_futures Awaitable[T]

Awaitables (coroutines or futures) to run concurrently

()
return_exceptions bool

If True, exceptions are returned instead of raised

False

Returns:

Type Description
Sequence[T | Exception]

A list of results in the same order as the input awaitables

Source code in src/anyenv/async_run.py
async def gather[T](
    *coros_or_futures: Awaitable[T],
    return_exceptions: bool = False,
) -> Sequence[T | Exception]:
    """Run awaitables concurrently using anyio's task groups.

    Like `asyncio.gather`, a failure raises the failing awaitable's own exception
    (the first one, if several fail), not an ExceptionGroup; the others are
    cancelled. Cancellation is never returned as a result.

    Args:
        *coros_or_futures: Awaitables (coroutines or futures) to run concurrently
        return_exceptions: If True, exceptions are returned instead of raised

    Returns:
        A list of results in the same order as the input awaitables
    """
    results: list[Any] = [None] * len(coros_or_futures)
    error: BaseException | None = None

    try:
        async with anyio.create_task_group() as tg:
            for i, coro in enumerate(coros_or_futures):

                async def run_and_store(idx: int = i, awaitable: Awaitable[T] = coro) -> None:
                    try:
                        results[idx] = await awaitable
                    except Exception as exc:
                        if return_exceptions:
                            results[idx] = exc
                        else:
                            raise

                tg.start_soon(run_and_store)
    except BaseExceptionGroup as group:
        # The task group's own wrapper: its members are the children's exceptions.
        error = group.exceptions[0]
    if error is not None:
        # Raised outside the except block, so its __context__ stays its own.
        raise error
    return results

run_in_thread async

run_in_thread(
    func: Callable[[*PosArgsT], T_Retval],
    *args: *PosArgsT,
    abandon_on_cancel: bool = False,
    cancellable: bool | None = None,
    limiter: Any = None,
    **kwargs: Any,
) -> T_Retval

Run a function in a separate thread using anyio.

Parameters:

Name Type Description Default
func Callable[[*PosArgsT], T_Retval]

The function to run in a thread

required
*args *PosArgsT

Positional arguments to pass to the function

()
abandon_on_cancel bool

Whether to abandon execution on cancellation

False
cancellable bool | None

Whether the operation can be cancelled

None
limiter Any

Optional capacity limiter for limiting concurrent threads

None
**kwargs Any

Keyword arguments to pass to the function

{}

Returns:

Type Description
T_Retval

The return value of the function

Source code in src/anyenv/async_run.py
async def run_in_thread[T_Retval, *PosArgsT](
    func: Callable[[*PosArgsT], T_Retval],
    *args: *PosArgsT,
    abandon_on_cancel: bool = False,
    cancellable: bool | None = None,
    limiter: Any = None,
    **kwargs: Any,
) -> T_Retval:
    """Run a function in a separate thread using anyio.

    Args:
        func: The function to run in a thread
        *args: Positional arguments to pass to the function
        abandon_on_cancel: Whether to abandon execution on cancellation
        cancellable: Whether the operation can be cancelled
        limiter: Optional capacity limiter for limiting concurrent threads
        **kwargs: Keyword arguments to pass to the function

    Returns:
        The return value of the function
    """
    fn: Callable[[*PosArgsT], T_Retval] = partial(func, **kwargs) if kwargs else func
    return await to_thread.run_sync(
        fn,
        *args,
        abandon_on_cancel=abandon_on_cancel,
        cancellable=cancellable,
        limiter=limiter,
    )

run_sync

run_sync(coro: Coroutine[Any, Any, T]) -> T

Run a coroutine synchronously.

This function uses anyio to run a coroutine in a synchronous context: outside an event loop with anyio's run function directly; inside one (an async frame calling sync code) in a new thread. The latter blocks the calling loop until the coroutine is done.

Context variables are properly propagated between threads in all cases.

Example:

async def f(x: int) -> int:
    return x + 1

result = run_sync(f(1))

Parameters:

Name Type Description Default
coro Coroutine[Any, Any, T]

The coroutine to run synchronously

required

Returns:

Type Description
T

The result of the coroutine

Source code in src/anyenv/async_run.py
def run_sync[T](coro: Coroutine[Any, Any, T]) -> T:
    """Run a coroutine synchronously.

    This function uses anyio to run a coroutine in a synchronous context:
    outside an event loop with anyio's run function directly; inside one (an
    async frame calling sync code) in a new thread. The latter blocks the calling
    loop until the coroutine is done.

    Context variables are properly propagated between threads in all cases.

    Example:
    ```python
    async def f(x: int) -> int:
        return x + 1

    result = run_sync(f(1))
    ```

    Args:
        coro: The coroutine to run synchronously

    Returns:
        The result of the coroutine
    """
    ctx = contextvars.copy_context()

    async def wrapper() -> T:
        return await coro

    # Decided upfront: retrying after a failure could re-run a coroutine that
    # already ran, and would misread the coroutine's own errors.
    if _in_event_loop():
        return run_sync_in_thread(coro)
    return ctx.run(anyio.run, wrapper)

run_sync_in_thread

run_sync_in_thread(coro: Coroutine[Any, Any, T]) -> T

Run a coroutine synchronously in a new thread.

This function creates a new thread to run the coroutine with anyio. Context variables are properly propagated between threads. This is useful when you need to run async code in a context where you can't use the current event loop (e.g., inside an async frame).

Example:

async def f(x: int) -> int:
    return x + 1

result = run_sync_in_thread(f(1))

Parameters:

Name Type Description Default
coro Coroutine[Any, Any, T]

The coroutine to run synchronously

required

Returns:

Type Description
T

The result of the coroutine

Source code in src/anyenv/async_run.py
def run_sync_in_thread[T](coro: Coroutine[Any, Any, T]) -> T:
    """Run a coroutine synchronously in a new thread.

    This function creates a new thread to run the coroutine with anyio.
    Context variables are properly propagated between threads.
    This is useful when you need to run async code in a context where you can't use
    the current event loop (e.g., inside an async frame).

    Example:
    ```python
    async def f(x: int) -> int:
        return x + 1

    result = run_sync_in_thread(f(1))
    ```

    Args:
        coro: The coroutine to run synchronously

    Returns:
        The result of the coroutine
    """
    result: T | None = None
    error: BaseException | None = None
    done = threading.Event()
    ctx = contextvars.copy_context()

    def thread_target() -> None:
        nonlocal result, error
        try:
            result = ctx.run(anyio.run, lambda: coro)
        except BaseException as e:  # noqa: BLE001
            error = e
        finally:
            done.set()

    thread = threading.Thread(target=thread_target)
    thread.start()
    done.wait()
    if error is not None:
        raise error
    return result  # type: ignore