async_compat.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """
  2. This file should only be imported from Python 3.
  3. It will raise SyntaxError when importing from Python 2.
  4. """
  5. import asyncio
  6. import inspect
  7. from functools import lru_cache
  8. from ray._private.ray_constants import env_bool
  9. try:
  10. import uvloop
  11. except ImportError:
  12. uvloop = None
  13. def get_new_event_loop():
  14. """Construct a new event loop. Ray will use uvloop if it exists and is enabled"""
  15. if uvloop and env_bool("RAY_USE_UVLOOP", True):
  16. return uvloop.new_event_loop()
  17. else:
  18. return asyncio.new_event_loop()
  19. def try_install_uvloop():
  20. """Installs uvloop as event-loop implementation for asyncio (if available and enabled)"""
  21. if uvloop and env_bool("RAY_USE_UVLOOP", True):
  22. uvloop.install()
  23. else:
  24. pass
  25. def is_async_func(func) -> bool:
  26. """Return True if the function is an async or async generator method."""
  27. return inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func)
  28. @lru_cache(maxsize=2**10)
  29. def has_async_methods(cls: object) -> bool:
  30. """Return True if the class has any async methods."""
  31. return len(inspect.getmembers(cls, predicate=is_async_func)) > 0
  32. @lru_cache(maxsize=2**10)
  33. def sync_to_async(func):
  34. """Wrap a blocking function in an async function"""
  35. if is_async_func(func):
  36. return func
  37. async def wrapper(*args, **kwargs):
  38. return func(*args, **kwargs)
  39. return wrapper