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
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: 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:
- Broadcast mode: Same args/kwargs for all callables
- 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
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
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
gather
async
¶
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
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
run_sync
¶
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:
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
run_sync_in_thread
¶
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:
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 |