util.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from typing import Optional, Union
  2. def convert_string_to_type(
  3. val: Optional[Union[str, int, float, bool]], convert_type: Union[int, float, bool]
  4. ) -> Union[int, float, bool]:
  5. """Convert the given value to a convert type.
  6. If the given val is None, it will just return None without the conversion.
  7. It supports,
  8. str -> int/float/bool
  9. int -> int
  10. bool -> bool
  11. float -> float
  12. """
  13. if val is None:
  14. return None
  15. elif type(val) is convert_type:
  16. return val
  17. elif convert_type is int:
  18. try:
  19. val = int(val)
  20. except ValueError:
  21. raise ValueError(
  22. f"Failed to convert a value {val} of type {type(val)} to {convert_type}"
  23. )
  24. elif convert_type is float:
  25. try:
  26. val = float(val)
  27. except ValueError:
  28. raise ValueError(
  29. f"Failed to convert a value {val} of type {type(val)} to {convert_type}"
  30. )
  31. elif convert_type is bool:
  32. # Without this, "False" will become True.
  33. if val == "False" or val == "false" or val == "0":
  34. val = False
  35. elif val == "True" or val == "true" or val == "1":
  36. val = True
  37. else:
  38. raise ValueError(
  39. f"Failed to convert a value {val} of type {type(val)} to {convert_type}"
  40. )
  41. else:
  42. assert False, f"Unsupported convert type {convert_type}"
  43. return val
  44. def record_deprecated_state_api_import():
  45. import warnings
  46. from ray._common.usage.usage_lib import TagKey, record_extra_usage_tag
  47. warnings.warn(
  48. "Ray state API is no longer experimental. Please import from `ray.util.state`. "
  49. "instead. Importing from `ray.experimental` will be deprecated in "
  50. "future releases. ",
  51. DeprecationWarning,
  52. )
  53. record_extra_usage_tag(TagKey.EXPERIMENTAL_STATE_API_IMPORT, "1")