converters.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. # SPDX-License-Identifier: MIT
  2. """
  3. Commonly useful converters.
  4. """
  5. import typing
  6. from ._compat import _AnnotationExtractor
  7. from ._make import NOTHING, Factory, pipe
  8. __all__ = [
  9. "default_if_none",
  10. "optional",
  11. "pipe",
  12. "to_bool",
  13. ]
  14. def optional(converter):
  15. """
  16. A converter that allows an attribute to be optional. An optional attribute
  17. is one which can be set to ``None``.
  18. Type annotations will be inferred from the wrapped converter's, if it
  19. has any.
  20. :param callable converter: the converter that is used for non-``None``
  21. values.
  22. .. versionadded:: 17.1.0
  23. """
  24. def optional_converter(val):
  25. if val is None:
  26. return None
  27. return converter(val)
  28. xtr = _AnnotationExtractor(converter)
  29. t = xtr.get_first_param_type()
  30. if t:
  31. optional_converter.__annotations__["val"] = typing.Optional[t]
  32. rt = xtr.get_return_type()
  33. if rt:
  34. optional_converter.__annotations__["return"] = typing.Optional[rt]
  35. return optional_converter
  36. def default_if_none(default=NOTHING, factory=None):
  37. """
  38. A converter that allows to replace ``None`` values by *default* or the
  39. result of *factory*.
  40. :param default: Value to be used if ``None`` is passed. Passing an instance
  41. of `attrs.Factory` is supported, however the ``takes_self`` option
  42. is *not*.
  43. :param callable factory: A callable that takes no parameters whose result
  44. is used if ``None`` is passed.
  45. :raises TypeError: If **neither** *default* or *factory* is passed.
  46. :raises TypeError: If **both** *default* and *factory* are passed.
  47. :raises ValueError: If an instance of `attrs.Factory` is passed with
  48. ``takes_self=True``.
  49. .. versionadded:: 18.2.0
  50. """
  51. if default is NOTHING and factory is None:
  52. msg = "Must pass either `default` or `factory`."
  53. raise TypeError(msg)
  54. if default is not NOTHING and factory is not None:
  55. msg = "Must pass either `default` or `factory` but not both."
  56. raise TypeError(msg)
  57. if factory is not None:
  58. default = Factory(factory)
  59. if isinstance(default, Factory):
  60. if default.takes_self:
  61. msg = "`takes_self` is not supported by default_if_none."
  62. raise ValueError(msg)
  63. def default_if_none_converter(val):
  64. if val is not None:
  65. return val
  66. return default.factory()
  67. else:
  68. def default_if_none_converter(val):
  69. if val is not None:
  70. return val
  71. return default
  72. return default_if_none_converter
  73. def to_bool(val):
  74. """
  75. Convert "boolean" strings (e.g., from env. vars.) to real booleans.
  76. Values mapping to :code:`True`:
  77. - :code:`True`
  78. - :code:`"true"` / :code:`"t"`
  79. - :code:`"yes"` / :code:`"y"`
  80. - :code:`"on"`
  81. - :code:`"1"`
  82. - :code:`1`
  83. Values mapping to :code:`False`:
  84. - :code:`False`
  85. - :code:`"false"` / :code:`"f"`
  86. - :code:`"no"` / :code:`"n"`
  87. - :code:`"off"`
  88. - :code:`"0"`
  89. - :code:`0`
  90. :raises ValueError: for any other value.
  91. .. versionadded:: 21.3.0
  92. """
  93. if isinstance(val, str):
  94. val = val.lower()
  95. truthy = {True, "true", "t", "yes", "y", "on", "1", 1}
  96. falsy = {False, "false", "f", "no", "n", "off", "0", 0}
  97. try:
  98. if val in truthy:
  99. return True
  100. if val in falsy:
  101. return False
  102. except TypeError:
  103. # Raised when "val" is not hashable (e.g., lists)
  104. pass
  105. msg = f"Cannot convert value to bool: {val}"
  106. raise ValueError(msg)