summaryrefslogtreecommitdiff
path: root/scalarbool.py
diff options
context:
space:
mode:
authorAnthon van der Neut <anthon@mnt.org>2018-12-28 17:14:28 +0100
committerAnthon van der Neut <anthon@mnt.org>2018-12-28 17:14:28 +0100
commit3ac28c509c0759a881ebfd06d300507e8db2c9d2 (patch)
tree1e12c26ddc454f101496c91729b60deeaa5c47a9 /scalarbool.py
parent96cf5fdbbfec1902fcaeeb3ba6c75ccf92f1f2f7 (diff)
downloadruamel.yaml-3ac28c509c0759a881ebfd06d300507e8db2c9d2.tar.gz
preserve anchors on scalars, on tagged objects0.15.82
fixes issue #63 fixes issue #266 *When this change indeed resolves your problem, please **Close** this issue*. *(You can do so using the WorkFlow pull-down (close to the top right of this page))*
Diffstat (limited to 'scalarbool.py')
-rw-r--r--scalarbool.py51
1 files changed, 51 insertions, 0 deletions
diff --git a/scalarbool.py b/scalarbool.py
new file mode 100644
index 0000000..fc8f8c2
--- /dev/null
+++ b/scalarbool.py
@@ -0,0 +1,51 @@
+# coding: utf-8
+
+from __future__ import print_function, absolute_import, division, unicode_literals
+
+"""
+You cannot subclass bool, and this is necessary for round-tripping anchored
+bool values (and also if you want to preserve the original way of writing)
+
+bool.__bases__ is type 'int', so that is what is used as the basis for ScalarBoolean as well.
+
+You can use these in an if statement, but not when testing equivalence
+"""
+
+from ruamel.yaml.anchor import Anchor
+
+if False: # MYPY
+ from typing import Text, Any, Dict, List # NOQA
+
+__all__ = ['ScalarBoolean']
+
+# no need for no_limit_int -> int
+
+
+class ScalarBoolean(int):
+ def __new__(cls, *args, **kw):
+ # type: (Any, Any, Any) -> Any
+ anchor = kw.pop('anchor', None) # type: ignore
+ b = int.__new__(cls, *args, **kw) # type: ignore
+ if anchor is not None:
+ b.yaml_set_anchor(anchor, always_dump=True)
+ return b
+
+ @property
+ def anchor(self):
+ # type: () -> Any
+ if not hasattr(self, Anchor.attrib):
+ setattr(self, Anchor.attrib, Anchor())
+ return getattr(self, Anchor.attrib)
+
+ def yaml_anchor(self, any=False):
+ # type: (bool) -> Any
+ if not hasattr(self, Anchor.attrib):
+ return None
+ if any or self.anchor.always_dump:
+ return self.anchor
+ return None
+
+ def yaml_set_anchor(self, value, always_dump=False):
+ # type: (Any, bool) -> None
+ self.anchor.value = value
+ self.anchor.always_dump = always_dump