Run a function in an executor. Args: executor (Executor): The executor. func (Callable[P, Output]): The function. *args (Any): The positional arguments to the function. **kwargs (Any): The keyword arguments to the function. Returns: Output: The outpu
(
executor_or_config: Optional[Union[Executor, RunnableConfig]],
func: Callable[P, T],
*args: P.args,
**kwargs: P.kwargs,
)
| 526 | |
| 527 | |
| 528 | async def run_in_executor( |
| 529 | executor_or_config: Optional[Union[Executor, RunnableConfig]], |
| 530 | func: Callable[P, T], |
| 531 | *args: P.args, |
| 532 | **kwargs: P.kwargs, |
| 533 | ) -> T: |
| 534 | """Run a function in an executor. |
| 535 | |
| 536 | Args: |
| 537 | executor (Executor): The executor. |
| 538 | func (Callable[P, Output]): The function. |
| 539 | *args (Any): The positional arguments to the function. |
| 540 | **kwargs (Any): The keyword arguments to the function. |
| 541 | |
| 542 | Returns: |
| 543 | Output: The output of the function. |
| 544 | """ |
| 545 | |
| 546 | def wrapper() -> T: |
| 547 | try: |
| 548 | return func(*args, **kwargs) |
| 549 | except StopIteration as exc: |
| 550 | # StopIteration can't be set on an asyncio.Future |
| 551 | # it raises a TypeError and leaves the Future pending forever |
| 552 | # so we need to convert it to a RuntimeError |
| 553 | raise RuntimeError from exc |
| 554 | |
| 555 | if executor_or_config is None or isinstance(executor_or_config, dict): |
| 556 | # Use default executor with context copied from current context |
| 557 | return await asyncio.get_running_loop().run_in_executor( |
| 558 | None, |
| 559 | cast(Callable[..., T], partial(copy_context().run, wrapper)), |
| 560 | ) |
| 561 | |
| 562 | return await asyncio.get_running_loop().run_in_executor(executor_or_config, wrapper) |
no outgoing calls