scalarbool.py 1.3 KB

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