MCPcopy Index your code
hub / github.com/python-openxml/python-docx / OptionalAttribute

Class OptionalAttribute

src/docx/oxml/xmlchemy.py:154–214  ·  view source on GitHub ↗

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, but still returns the default value when one is specified.

Source from the content-addressed store, hash-verified

152
153
154class OptionalAttribute(BaseAttribute):
155 """Defines an optional attribute on a custom element class.
156
157 An optional attribute returns a default value when not present for reading. When
158 assigned |None|, the attribute is removed, but still returns the default value when
159 one is specified.
160 """
161
162 def __init__(
163 self,
164 attr_name: str,
165 simple_type: Type[BaseXmlEnum] | Type[BaseSimpleType],
166 default: BaseXmlEnum | BaseSimpleType | str | bool | None = None,
167 ):
168 super(OptionalAttribute, self).__init__(attr_name, simple_type)
169 self._default = default
170
171 @property
172 def _docstring(self):
173 """String to use as `__doc__` attribute of attribute property."""
174 return (
175 f"{self._simple_type.__name__} type-converted value of"
176 f" ``{self._attr_name}`` attribute, or |None| (or specified default"
177 f" value) if not present. Assigning the default value causes the"
178 f" attribute to be removed from the element."
179 )
180
181 @property
182 def _getter(
183 self,
184 ) -> Callable[[BaseOxmlElement], Any | None]:
185 """Function suitable for `__get__()` method on attribute property descriptor."""
186
187 def get_attr_value(
188 obj: BaseOxmlElement,
189 ) -> Any | None:
190 attr_str_value = obj.get(self._clark_name)
191 if attr_str_value is None:
192 return self._default
193 return self._simple_type.from_xml(attr_str_value)
194
195 get_attr_value.__doc__ = self._docstring
196 return get_attr_value
197
198 @property
199 def _setter(self) -> Callable[[BaseOxmlElement, Any], None]:
200 """Function suitable for `__set__()` method on attribute property descriptor."""
201
202 def set_attr_value(obj: BaseOxmlElement, value: Any | None):
203 if value is None or value == self._default:
204 if self._clark_name in obj.attrib:
205 del obj.attrib[self._clark_name]
206 return
207 str_value = self._simple_type.to_xml(value)
208 if str_value is None:
209 if self._clark_name in obj.attrib:
210 del obj.attrib[self._clark_name]
211 return

Callers 15

CT_CommentClass · 0.90
CT_OnOffClass · 0.90
CT_HeightClass · 0.90
CT_TblGridColClass · 0.90
CT_TblLayoutTypeClass · 0.90
CT_VMergeClass · 0.90
CT_LatentStylesClass · 0.90
CT_LsdExceptionClass · 0.90
CT_StyleClass · 0.90
CT_PageMarClass · 0.90
CT_PageSzClass · 0.90
CT_SectTypeClass · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…