Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/openpyxl/descriptors/nested.py: 84%
62 statements
« prev ^ index » next coverage.py v7.3.3, created at 2023-12-20 06:34 +0000
« prev ^ index » next coverage.py v7.3.3, created at 2023-12-20 06:34 +0000
1# Copyright (c) 2010-2023 openpyxl
3"""
4Generic serialisable classes
5"""
6from .base import (
7 Convertible,
8 Bool,
9 Descriptor,
10 NoneSet,
11 MinMax,
12 Set,
13 Float,
14 Integer,
15 String,
16 Text,
17 )
18from .sequence import Sequence
19from openpyxl.compat import safe_string
20from openpyxl.xml.functions import Element, localname, whitespace
23class Nested(Descriptor):
25 nested = True
26 attribute = "val"
28 def __set__(self, instance, value):
29 if hasattr(value, "tag"):
30 tag = localname(value)
31 if tag != self.name:
32 raise ValueError("Tag does not match attribute")
34 value = self.from_tree(value)
35 super(Nested, self).__set__(instance, value)
38 def from_tree(self, node):
39 return node.get(self.attribute)
42 def to_tree(self, tagname=None, value=None, namespace=None):
43 namespace = getattr(self, "namespace", namespace)
44 if value is not None:
45 if namespace is not None:
46 tagname = "{%s}%s" % (namespace, tagname)
47 value = safe_string(value)
48 return Element(tagname, {self.attribute:value})
51class NestedValue(Nested, Convertible):
52 """
53 Nested tag storing the value on the 'val' attribute
54 """
55 pass
58class NestedText(NestedValue):
59 """
60 Represents any nested tag with the value as the contents of the tag
61 """
64 def from_tree(self, node):
65 return node.text
68 def to_tree(self, tagname=None, value=None, namespace=None):
69 namespace = getattr(self, "namespace", namespace)
70 if value is not None:
71 if namespace is not None:
72 tagname = "{%s}%s" % (namespace, tagname)
73 el = Element(tagname)
74 el.text = safe_string(value)
75 whitespace(el)
76 return el
79class NestedFloat(NestedValue, Float):
81 pass
84class NestedInteger(NestedValue, Integer):
86 pass
89class NestedString(NestedValue, String):
91 pass
94class NestedBool(NestedValue, Bool):
97 def from_tree(self, node):
98 return node.get("val", True)
101class NestedNoneSet(Nested, NoneSet):
103 pass
106class NestedSet(Nested, Set):
108 pass
111class NestedMinMax(Nested, MinMax):
113 pass
116class EmptyTag(Nested, Bool):
118 """
119 Boolean if a tag exists or not.
120 """
122 def from_tree(self, node):
123 return True
126 def to_tree(self, tagname=None, value=None, namespace=None):
127 if value:
128 namespace = getattr(self, "namespace", namespace)
129 if namespace is not None:
130 tagname = "{%s}%s" % (namespace, tagname)
131 return Element(tagname)