Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/anyio/to_thread.py: 70%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3__all__ = (
4 "run_sync",
5 "current_default_thread_limiter",
6)
8import sys
9from collections.abc import Callable
10from typing import TypeVar
11from warnings import warn
13from ._core._eventloop import get_async_backend
14from .abc import CapacityLimiter
16if sys.version_info >= (3, 11):
17 from typing import TypeVarTuple, Unpack
18else:
19 from typing_extensions import TypeVarTuple, Unpack
21T_Retval = TypeVar("T_Retval")
22PosArgsT = TypeVarTuple("PosArgsT")
25async def run_sync(
26 func: Callable[[Unpack[PosArgsT]], T_Retval],
27 *args: Unpack[PosArgsT],
28 abandon_on_cancel: bool = False,
29 cancellable: bool | None = None,
30 limiter: CapacityLimiter | None = None,
31) -> T_Retval:
32 """
33 Call the given function with the given arguments in a worker thread.
35 If the ``cancellable`` option is enabled and the task waiting for its completion is
36 cancelled, the thread will still run its course but its return value (or any raised
37 exception) will be ignored.
39 :param func: a callable
40 :param args: positional arguments for the callable
41 :param abandon_on_cancel: ``True`` to abandon the thread (leaving it to run
42 unchecked on own) if the host task is cancelled, ``False`` to ignore
43 cancellations in the host task until the operation has completed in the worker
44 thread
45 :param cancellable: deprecated alias of ``abandon_on_cancel``; will override
46 ``abandon_on_cancel`` if both parameters are passed
47 :param limiter: capacity limiter to use to limit the total amount of threads running
48 (if omitted, the default limiter is used)
49 :raises NoEventLoopError: if no supported asynchronous event loop is running in the
50 current thread
51 :return: an awaitable that yields the return value of the function.
53 """
54 if cancellable is not None:
55 abandon_on_cancel = cancellable
56 warn(
57 "The `cancellable=` keyword argument to `anyio.to_thread.run_sync` is "
58 "deprecated since AnyIO 4.1.0; use `abandon_on_cancel=` instead",
59 DeprecationWarning,
60 stacklevel=2,
61 )
63 return await get_async_backend().run_sync_in_worker_thread(
64 func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter
65 )
68def current_default_thread_limiter() -> CapacityLimiter:
69 """
70 Return the capacity limiter that is used by default to limit the number of
71 concurrent threads.
73 :return: a capacity limiter object
74 :raises NoEventLoopError: if no supported asynchronous event loop is running in the
75 current thread
77 """
78 return get_async_backend().current_default_thread_limiter()