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

20 statements  

1from __future__ import annotations 

2 

3__all__ = ( 

4 "run_sync", 

5 "current_default_thread_limiter", 

6) 

7 

8import sys 

9from collections.abc import Callable 

10from typing import TypeVar 

11from warnings import warn 

12 

13from ._core._eventloop import get_async_backend 

14from .abc import CapacityLimiter 

15 

16if sys.version_info >= (3, 11): 

17 from typing import TypeVarTuple, Unpack 

18else: 

19 from typing_extensions import TypeVarTuple, Unpack 

20 

21T_Retval = TypeVar("T_Retval") 

22PosArgsT = TypeVarTuple("PosArgsT") 

23 

24 

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. 

34 

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. 

38 

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 :return: an awaitable that yields the return value of the function. 

50 

51 """ 

52 if cancellable is not None: 

53 abandon_on_cancel = cancellable 

54 warn( 

55 "The `cancellable=` keyword argument to `anyio.to_thread.run_sync` is " 

56 "deprecated since AnyIO 4.1.0; use `abandon_on_cancel=` instead", 

57 DeprecationWarning, 

58 stacklevel=2, 

59 ) 

60 

61 return await get_async_backend().run_sync_in_worker_thread( 

62 func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter 

63 ) 

64 

65 

66def current_default_thread_limiter() -> CapacityLimiter: 

67 """ 

68 Return the capacity limiter that is used by default to limit the number of 

69 concurrent threads. 

70 

71 :return: a capacity limiter object 

72 

73 """ 

74 return get_async_backend().current_default_thread_limiter()