setters.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # SPDX-License-Identifier: MIT
  2. """
  3. Commonly used hooks for on_setattr.
  4. """
  5. from __future__ import absolute_import, division, print_function
  6. from . import _config
  7. from .exceptions import FrozenAttributeError
  8. def pipe(*setters):
  9. """
  10. Run all *setters* and return the return value of the last one.
  11. .. versionadded:: 20.1.0
  12. """
  13. def wrapped_pipe(instance, attrib, new_value):
  14. rv = new_value
  15. for setter in setters:
  16. rv = setter(instance, attrib, rv)
  17. return rv
  18. return wrapped_pipe
  19. def frozen(_, __, ___):
  20. """
  21. Prevent an attribute to be modified.
  22. .. versionadded:: 20.1.0
  23. """
  24. raise FrozenAttributeError()
  25. def validate(instance, attrib, new_value):
  26. """
  27. Run *attrib*'s validator on *new_value* if it has one.
  28. .. versionadded:: 20.1.0
  29. """
  30. if _config._run_validators is False:
  31. return new_value
  32. v = attrib.validator
  33. if not v:
  34. return new_value
  35. v(instance, attrib, new_value)
  36. return new_value
  37. def convert(instance, attrib, new_value):
  38. """
  39. Run *attrib*'s converter -- if it has one -- on *new_value* and return the
  40. result.
  41. .. versionadded:: 20.1.0
  42. """
  43. c = attrib.converter
  44. if c:
  45. return c(new_value)
  46. return new_value
  47. NO_OP = object()
  48. """
  49. Sentinel for disabling class-wide *on_setattr* hooks for certain attributes.
  50. Does not work in `pipe` or within lists.
  51. .. versionadded:: 20.1.0
  52. """