converters.py 4.0 KB

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