Defines an optional attribute on a custom element class. An optional attribute returns a default value when not present for reading. When assigned |None|, the attribute is removed.
| 175 | |
| 176 | |
| 177 | class OptionalAttribute(BaseAttribute): |
| 178 | """Defines an optional attribute on a custom element class. |
| 179 | |
| 180 | An optional attribute returns a default value when not present for reading. When assigned |
| 181 | |None|, the attribute is removed. |
| 182 | """ |
| 183 | |
| 184 | def __init__(self, attr_name: str, simple_type: type[AttributeType], default: Any = None): |
| 185 | super(OptionalAttribute, self).__init__(attr_name, simple_type) |
| 186 | self._default = default |
| 187 | |
| 188 | @property |
| 189 | def _docstring(self): |
| 190 | """ |
| 191 | Return the string to use as the ``__doc__`` attribute of the property |
| 192 | for this attribute. |
| 193 | """ |
| 194 | return ( |
| 195 | "%s type-converted value of ``%s`` attribute, or |None| (or spec" |
| 196 | "ified default value) if not present. Assigning the default valu" |
| 197 | "e causes the attribute to be removed from the element." |
| 198 | % (self._simple_type.__name__, self._attr_name) |
| 199 | ) |
| 200 | |
| 201 | @property |
| 202 | def _getter(self) -> Callable[[BaseOxmlElement], Any]: |
| 203 | """Callable suitable for the "get" side of the attribute property descriptor.""" |
| 204 | |
| 205 | def get_attr_value(obj: BaseOxmlElement) -> Any: |
| 206 | attr_str_value = obj.get(self._clark_name) |
| 207 | if attr_str_value is None: |
| 208 | return self._default |
| 209 | return self._simple_type.from_xml(attr_str_value) |
| 210 | |
| 211 | get_attr_value.__doc__ = self._docstring |
| 212 | return get_attr_value |
| 213 | |
| 214 | @property |
| 215 | def _setter(self) -> Callable[[BaseOxmlElement, Any], None]: |
| 216 | """Callable suitable for the "set" side of the attribute property descriptor.""" |
| 217 | |
| 218 | def set_attr_value(obj: BaseOxmlElement, value: Any) -> None: |
| 219 | # -- when an XML attribute has a default value, setting it to that default removes the |
| 220 | # -- attribute from the element (when it is present) |
| 221 | if value == self._default: |
| 222 | if self._clark_name in obj.attrib: |
| 223 | del obj.attrib[self._clark_name] |
| 224 | return |
| 225 | str_value = self._simple_type.to_xml(value) |
| 226 | obj.set(self._clark_name, str_value) |
| 227 | |
| 228 | return set_attr_value |
| 229 | |
| 230 | |
| 231 | class RequiredAttribute(BaseAttribute): |
no outgoing calls
no test coverage detected
searching dependent graphs…