scalarbool.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # coding: utf-8
  2. from __future__ import print_function, absolute_import, division, unicode_literals
  3. """
  4. You cannot subclass bool, and this is necessary for round-tripping anchored
  5. bool values (and also if you want to preserve the original way of writing)
  6. bool.__bases__ is type 'int', so that is what is used as the basis for ScalarBoolean as well.
  7. You can use these in an if statement, but not when testing equivalence
  8. """
  9. from ruamel.yaml.anchor import Anchor
  10. if False: # MYPY
  11. from typing import Text, Any, Dict, List # NOQA
  12. __all__ = ['ScalarBoolean']
  13. # no need for no_limit_int -> int
  14. class ScalarBoolean(int):
  15. def __new__(cls, *args, **kw):
  16. # type: (Any, Any, Any) -> Any
  17. anchor = kw.pop('anchor', None) # type: ignore
  18. b = int.__new__(cls, *args, **kw) # type: ignore
  19. if anchor is not None:
  20. b.yaml_set_anchor(anchor, always_dump=True)
  21. return b
  22. @property
  23. def anchor(self):
  24. # type: () -> Any
  25. if not hasattr(self, Anchor.attrib):
  26. setattr(self, Anchor.attrib, Anchor())
  27. return getattr(self, Anchor.attrib)
  28. def yaml_anchor(self, any=False):
  29. # type: (bool) -> Any
  30. if not hasattr(self, Anchor.attrib):
  31. return None
  32. if any or self.anchor.always_dump:
  33. return self.anchor
  34. return None
  35. def yaml_set_anchor(self, value, always_dump=False):
  36. # type: (Any, bool) -> None
  37. self.anchor.value = value
  38. self.anchor.always_dump = always_dump