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 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """
  2. Commonly useful converters.
  3. """
  4. from __future__ import absolute_import, division, print_function
  5. from ._make import NOTHING, Factory
  6. def optional(converter):
  7. """
  8. A converter that allows an attribute to be optional. An optional attribute
  9. is one which can be set to ``None``.
  10. :param callable converter: the converter that is used for non-``None``
  11. values.
  12. .. versionadded:: 17.1.0
  13. """
  14. def optional_converter(val):
  15. if val is None:
  16. return None
  17. return converter(val)
  18. return optional_converter
  19. def default_if_none(default=NOTHING, factory=None):
  20. """
  21. A converter that allows to replace ``None`` values by *default* or the
  22. result of *factory*.
  23. :param default: Value to be used if ``None`` is passed. Passing an instance
  24. of `attr.Factory` is supported, however the ``takes_self`` option
  25. is *not*.
  26. :param callable factory: A callable that takes not parameters whose result
  27. is used if ``None`` is passed.
  28. :raises TypeError: If **neither** *default* or *factory* is passed.
  29. :raises TypeError: If **both** *default* and *factory* are passed.
  30. :raises ValueError: If an instance of `attr.Factory` is passed with
  31. ``takes_self=True``.
  32. .. versionadded:: 18.2.0
  33. """
  34. if default is NOTHING and factory is None:
  35. raise TypeError("Must pass either `default` or `factory`.")
  36. if default is not NOTHING and factory is not None:
  37. raise TypeError(
  38. "Must pass either `default` or `factory` but not both."
  39. )
  40. if factory is not None:
  41. default = Factory(factory)
  42. if isinstance(default, Factory):
  43. if default.takes_self:
  44. raise ValueError(
  45. "`takes_self` is not supported by default_if_none."
  46. )
  47. def default_if_none_converter(val):
  48. if val is not None:
  49. return val
  50. return default.factory()
  51. else:
  52. def default_if_none_converter(val):
  53. if val is not None:
  54. return val
  55. return default
  56. return default_if_none_converter