types.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. from distutils.util import strtobool
  2. from typing import Optional
  3. from typing import Tuple
  4. from typing import Union
  5. import humanfriendly
  6. def str2bool(value: str) -> bool:
  7. return bool(strtobool(value))
  8. def remove_parenthesis(value: str):
  9. value = value.strip()
  10. if value.startswith("(") and value.endswith(")"):
  11. value = value[1:-1]
  12. elif value.startswith("[") and value.endswith("]"):
  13. value = value[1:-1]
  14. return value
  15. def remove_quotes(value: str):
  16. value = value.strip()
  17. if value.startswith('"') and value.endswith('"'):
  18. value = value[1:-1]
  19. elif value.startswith("'") and value.endswith("'"):
  20. value = value[1:-1]
  21. return value
  22. def int_or_none(value: str) -> Optional[int]:
  23. """int_or_none.
  24. Examples:
  25. >>> import argparse
  26. >>> parser = argparse.ArgumentParser()
  27. >>> _ = parser.add_argument('--foo', type=int_or_none)
  28. >>> parser.parse_args(['--foo', '456'])
  29. Namespace(foo=456)
  30. >>> parser.parse_args(['--foo', 'none'])
  31. Namespace(foo=None)
  32. >>> parser.parse_args(['--foo', 'null'])
  33. Namespace(foo=None)
  34. >>> parser.parse_args(['--foo', 'nil'])
  35. Namespace(foo=None)
  36. """
  37. if value.strip().lower() in ("none", "null", "nil"):
  38. return None
  39. return int(value)
  40. def float_or_none(value: str) -> Optional[float]:
  41. """float_or_none.
  42. Examples:
  43. >>> import argparse
  44. >>> parser = argparse.ArgumentParser()
  45. >>> _ = parser.add_argument('--foo', type=float_or_none)
  46. >>> parser.parse_args(['--foo', '4.5'])
  47. Namespace(foo=4.5)
  48. >>> parser.parse_args(['--foo', 'none'])
  49. Namespace(foo=None)
  50. >>> parser.parse_args(['--foo', 'null'])
  51. Namespace(foo=None)
  52. >>> parser.parse_args(['--foo', 'nil'])
  53. Namespace(foo=None)
  54. """
  55. if value.strip().lower() in ("none", "null", "nil"):
  56. return None
  57. return float(value)
  58. def humanfriendly_parse_size_or_none(value) -> Optional[float]:
  59. if value.strip().lower() in ("none", "null", "nil"):
  60. return None
  61. return humanfriendly.parse_size(value)
  62. def str_or_int(value: str) -> Union[str, int]:
  63. try:
  64. return int(value)
  65. except ValueError:
  66. return value
  67. def str_or_none(value: str) -> Optional[str]:
  68. """str_or_none.
  69. Examples:
  70. >>> import argparse
  71. >>> parser = argparse.ArgumentParser()
  72. >>> _ = parser.add_argument('--foo', type=str_or_none)
  73. >>> parser.parse_args(['--foo', 'aaa'])
  74. Namespace(foo='aaa')
  75. >>> parser.parse_args(['--foo', 'none'])
  76. Namespace(foo=None)
  77. >>> parser.parse_args(['--foo', 'null'])
  78. Namespace(foo=None)
  79. >>> parser.parse_args(['--foo', 'nil'])
  80. Namespace(foo=None)
  81. """
  82. if value.strip().lower() in ("none", "null", "nil"):
  83. return None
  84. return value
  85. def str2pair_str(value: str) -> Tuple[str, str]:
  86. """str2pair_str.
  87. Examples:
  88. >>> import argparse
  89. >>> str2pair_str('abc,def ')
  90. ('abc', 'def')
  91. >>> parser = argparse.ArgumentParser()
  92. >>> _ = parser.add_argument('--foo', type=str2pair_str)
  93. >>> parser.parse_args(['--foo', 'abc,def'])
  94. Namespace(foo=('abc', 'def'))
  95. """
  96. value = remove_parenthesis(value)
  97. a, b = value.split(",")
  98. # Workaround for configargparse issues:
  99. # If the list values are given from yaml file,
  100. # the value givent to type() is shaped as python-list,
  101. # e.g. ['a', 'b', 'c'],
  102. # so we need to remove double quotes from it.
  103. return remove_quotes(a), remove_quotes(b)
  104. def str2triple_str(value: str) -> Tuple[str, str, str]:
  105. """str2triple_str.
  106. Examples:
  107. >>> str2triple_str('abc,def ,ghi')
  108. ('abc', 'def', 'ghi')
  109. """
  110. value = remove_parenthesis(value)
  111. a, b, c = value.split(",")
  112. # Workaround for configargparse issues:
  113. # If the list values are given from yaml file,
  114. # the value givent to type() is shaped as python-list,
  115. # e.g. ['a', 'b', 'c'],
  116. # so we need to remove quotes from it.
  117. return remove_quotes(a), remove_quotes(b), remove_quotes(c)