Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

64 lignes
1.7 KiB

  1. from __future__ import annotations
  2. import functools
  3. import sys
  4. import warnings
  5. from collections.abc import AsyncIterator, Coroutine, Iterable, Iterator
  6. from typing import Callable, TypeVar
  7. import anyio.to_thread
  8. if sys.version_info >= (3, 10): # pragma: no cover
  9. from typing import ParamSpec
  10. else: # pragma: no cover
  11. from typing_extensions import ParamSpec
  12. P = ParamSpec("P")
  13. T = TypeVar("T")
  14. async def run_until_first_complete(*args: tuple[Callable, dict]) -> None: # type: ignore[type-arg]
  15. warnings.warn(
  16. "run_until_first_complete is deprecated and will be removed in a future version.",
  17. DeprecationWarning,
  18. )
  19. async with anyio.create_task_group() as task_group:
  20. async def run(func: Callable[[], Coroutine]) -> None: # type: ignore[type-arg]
  21. await func()
  22. task_group.cancel_scope.cancel()
  23. for func, kwargs in args:
  24. task_group.start_soon(run, functools.partial(func, **kwargs))
  25. async def run_in_threadpool(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
  26. func = functools.partial(func, *args, **kwargs)
  27. return await anyio.to_thread.run_sync(func)
  28. class _StopIteration(Exception):
  29. pass
  30. def _next(iterator: Iterator[T]) -> T:
  31. # We can't raise `StopIteration` from within the threadpool iterator
  32. # and catch it outside that context, so we coerce them into a different
  33. # exception type.
  34. try:
  35. return next(iterator)
  36. except StopIteration:
  37. raise _StopIteration
  38. async def iterate_in_threadpool(
  39. iterator: Iterable[T],
  40. ) -> AsyncIterator[T]:
  41. as_iterator = iter(iterator)
  42. while True:
  43. try:
  44. yield await anyio.to_thread.run_sync(_next, as_iterator)
  45. except _StopIteration:
  46. break