Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

converters.py 3.5KB

1 year ago
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. raise TypeError("Must pass either `default` or `factory`.")
  53. if default is not NOTHING and factory is not None:
  54. raise TypeError(
  55. "Must pass either `default` or `factory` but not both."
  56. )
  57. if factory is not None:
  58. default = Factory(factory)
  59. if isinstance(default, Factory):
  60. if default.takes_self:
  61. raise ValueError(
  62. "`takes_self` is not supported by default_if_none."
  63. )
  64. def default_if_none_converter(val):
  65. if val is not None:
  66. return val
  67. return default.factory()
  68. else:
  69. def default_if_none_converter(val):
  70. if val is not None:
  71. return val
  72. return default
  73. return default_if_none_converter
  74. def to_bool(val):
  75. """
  76. Convert "boolean" strings (e.g., from env. vars.) to real booleans.
  77. Values mapping to :code:`True`:
  78. - :code:`True`
  79. - :code:`"true"` / :code:`"t"`
  80. - :code:`"yes"` / :code:`"y"`
  81. - :code:`"on"`
  82. - :code:`"1"`
  83. - :code:`1`
  84. Values mapping to :code:`False`:
  85. - :code:`False`
  86. - :code:`"false"` / :code:`"f"`
  87. - :code:`"no"` / :code:`"n"`
  88. - :code:`"off"`
  89. - :code:`"0"`
  90. - :code:`0`
  91. :raises ValueError: for any other value.
  92. .. versionadded:: 21.3.0
  93. """
  94. if isinstance(val, str):
  95. val = val.lower()
  96. truthy = {True, "true", "t", "yes", "y", "on", "1", 1}
  97. falsy = {False, "false", "f", "no", "n", "off", "0", 0}
  98. try:
  99. if val in truthy:
  100. return True
  101. if val in falsy:
  102. return False
  103. except TypeError:
  104. # Raised when "val" is not hashable (e.g., lists)
  105. pass
  106. raise ValueError(f"Cannot convert value to bool: {val}")