ps-python-docx 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. docx/__init__.py +68 -0
  2. docx/api.py +37 -0
  3. docx/blkcntnr.py +101 -0
  4. docx/comments.py +163 -0
  5. docx/dml/__init__.py +0 -0
  6. docx/dml/color.py +112 -0
  7. docx/document.py +275 -0
  8. docx/drawing/__init__.py +59 -0
  9. docx/enum/__init__.py +0 -0
  10. docx/enum/base.py +150 -0
  11. docx/enum/dml.py +103 -0
  12. docx/enum/section.py +86 -0
  13. docx/enum/shape.py +19 -0
  14. docx/enum/style.py +452 -0
  15. docx/enum/table.py +136 -0
  16. docx/enum/text.py +367 -0
  17. docx/exceptions.py +18 -0
  18. docx/image/__init__.py +23 -0
  19. docx/image/bmp.py +43 -0
  20. docx/image/constants.py +172 -0
  21. docx/image/exceptions.py +13 -0
  22. docx/image/gif.py +38 -0
  23. docx/image/helpers.py +86 -0
  24. docx/image/image.py +234 -0
  25. docx/image/jpeg.py +425 -0
  26. docx/image/png.py +253 -0
  27. docx/image/tiff.py +289 -0
  28. docx/opc/__init__.py +0 -0
  29. docx/opc/constants.py +306 -0
  30. docx/opc/coreprops.py +142 -0
  31. docx/opc/exceptions.py +12 -0
  32. docx/opc/oxml.py +247 -0
  33. docx/opc/package.py +219 -0
  34. docx/opc/packuri.py +109 -0
  35. docx/opc/part.py +247 -0
  36. docx/opc/parts/__init__.py +0 -0
  37. docx/opc/parts/coreprops.py +48 -0
  38. docx/opc/phys_pkg.py +119 -0
  39. docx/opc/pkgreader.py +254 -0
  40. docx/opc/pkgwriter.py +115 -0
  41. docx/opc/rel.py +153 -0
  42. docx/opc/shared.py +31 -0
  43. docx/opc/spec.py +24 -0
  44. docx/oxml/__init__.py +261 -0
  45. docx/oxml/comments.py +124 -0
  46. docx/oxml/coreprops.py +298 -0
  47. docx/oxml/document.py +88 -0
  48. docx/oxml/drawing.py +11 -0
  49. docx/oxml/exceptions.py +10 -0
  50. docx/oxml/ns.py +109 -0
  51. docx/oxml/numbering.py +109 -0
  52. docx/oxml/parser.py +62 -0
  53. docx/oxml/section.py +537 -0
  54. docx/oxml/settings.py +138 -0
  55. docx/oxml/shape.py +299 -0
  56. docx/oxml/shared.py +52 -0
  57. docx/oxml/simpletypes.py +434 -0
  58. docx/oxml/styles.py +341 -0
  59. docx/oxml/table.py +977 -0
  60. docx/oxml/text/__init__.py +0 -0
  61. docx/oxml/text/font.py +333 -0
  62. docx/oxml/text/hyperlink.py +45 -0
  63. docx/oxml/text/pagebreak.py +278 -0
  64. docx/oxml/text/paragraph.py +106 -0
  65. docx/oxml/text/parfmt.py +392 -0
  66. docx/oxml/text/run.py +307 -0
  67. docx/oxml/xmlchemy.py +696 -0
  68. docx/package.py +110 -0
  69. docx/parts/__init__.py +0 -0
  70. docx/parts/comments.py +51 -0
  71. docx/parts/document.py +182 -0
  72. docx/parts/hdrftr.py +53 -0
  73. docx/parts/image.py +80 -0
  74. docx/parts/numbering.py +32 -0
  75. docx/parts/settings.py +50 -0
  76. docx/parts/story.py +95 -0
  77. docx/parts/styles.py +42 -0
  78. docx/parts/theme.py +53 -0
  79. docx/py.typed +0 -0
  80. docx/section.py +479 -0
  81. docx/settings.py +35 -0
  82. docx/shape.py +103 -0
  83. docx/shared.py +382 -0
  84. docx/styles/__init__.py +40 -0
  85. docx/styles/latent.py +198 -0
  86. docx/styles/style.py +264 -0
  87. docx/styles/styles.py +147 -0
  88. docx/table.py +537 -0
  89. docx/templates/default-comments.xml +12 -0
  90. docx/templates/default-docx-template/[Content_Types].xml +17 -0
  91. docx/templates/default-docx-template/_rels/.rels +7 -0
  92. docx/templates/default-docx-template/customXml/_rels/item1.xml.rels +4 -0
  93. docx/templates/default-docx-template/customXml/item1.xml +2 -0
  94. docx/templates/default-docx-template/customXml/itemProps1.xml +6 -0
  95. docx/templates/default-docx-template/docProps/app.xml +36 -0
  96. docx/templates/default-docx-template/docProps/core.xml +13 -0
  97. docx/templates/default-docx-template/docProps/thumbnail.jpeg +0 -0
  98. docx/templates/default-docx-template/word/_rels/document.xml.rels +11 -0
  99. docx/templates/default-docx-template/word/document.xml +11 -0
  100. docx/templates/default-docx-template/word/fontTable.xml +61 -0
  101. docx/templates/default-docx-template/word/numbering.xml +201 -0
  102. docx/templates/default-docx-template/word/settings.xml +53 -0
  103. docx/templates/default-docx-template/word/styles.xml +11844 -0
  104. docx/templates/default-docx-template/word/stylesWithEffects.xml +11800 -0
  105. docx/templates/default-docx-template/word/theme/theme1.xml +318 -0
  106. docx/templates/default-docx-template/word/webSettings.xml +5 -0
  107. docx/templates/default-footer.xml +27 -0
  108. docx/templates/default-header.xml +27 -0
  109. docx/templates/default-settings.xml +26 -0
  110. docx/templates/default-styles.xml +190 -0
  111. docx/templates/default.docx +0 -0
  112. docx/text/__init__.py +0 -0
  113. docx/text/font.py +472 -0
  114. docx/text/hyperlink.py +121 -0
  115. docx/text/pagebreak.py +104 -0
  116. docx/text/paragraph.py +173 -0
  117. docx/text/parfmt.py +286 -0
  118. docx/text/run.py +257 -0
  119. docx/text/tabstops.py +123 -0
  120. docx/theme.py +67 -0
  121. docx/types.py +34 -0
  122. ps_python_docx-1.3.0.dist-info/METADATA +77 -0
  123. ps_python_docx-1.3.0.dist-info/RECORD +126 -0
  124. ps_python_docx-1.3.0.dist-info/WHEEL +5 -0
  125. ps_python_docx-1.3.0.dist-info/licenses/LICENSE +20 -0
  126. ps_python_docx-1.3.0.dist-info/top_level.txt +1 -0
docx/oxml/xmlchemy.py ADDED
@@ -0,0 +1,696 @@
1
+ # pyright: reportImportCycles=false
2
+
3
+ """Enabling declarative definition of lxml custom element classes."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from typing import TYPE_CHECKING, Any, Callable, Sequence, Type, TypeVar
9
+
10
+ from lxml import etree
11
+ from lxml.etree import ElementBase, _Element # pyright: ignore[reportPrivateUsage]
12
+
13
+ from docx.oxml.exceptions import InvalidXmlError
14
+ from docx.oxml.ns import NamespacePrefixedTag, nsmap, qn
15
+ from docx.shared import lazyproperty
16
+
17
+ if TYPE_CHECKING:
18
+ from docx.enum.base import BaseXmlEnum
19
+ from docx.oxml.simpletypes import BaseSimpleType
20
+
21
+
22
+ def serialize_for_reading(element: ElementBase):
23
+ """Serialize `element` to human-readable XML suitable for tests.
24
+
25
+ No XML declaration.
26
+ """
27
+ xml = etree.tostring(element, encoding="unicode", pretty_print=True)
28
+ return XmlString(xml)
29
+
30
+
31
+ class XmlString(str):
32
+ """Provides string comparison override suitable for serialized XML that is useful
33
+ for tests."""
34
+
35
+ # ' <w:xyz xmlns:a="http://ns/decl/a" attr_name="val">text</w:xyz>'
36
+ # | | || |
37
+ # +----------+------------------------------------------++-----------+
38
+ # front attrs | text
39
+ # close
40
+
41
+ _xml_elm_line_patt = re.compile(r"( *</?[\w:]+)(.*?)(/?>)([^<]*</[\w:]+>)?$")
42
+
43
+ def __eq__(self, other: object) -> bool:
44
+ if not isinstance(other, str):
45
+ return False
46
+ lines = self.splitlines()
47
+ lines_other = other.splitlines()
48
+ if len(lines) != len(lines_other):
49
+ return False
50
+ for line, line_other in zip(lines, lines_other):
51
+ if not self._eq_elm_strs(line, line_other):
52
+ return False
53
+ return True
54
+
55
+ def __ne__(self, other: object) -> bool:
56
+ return not self.__eq__(other)
57
+
58
+ def _attr_seq(self, attrs: str) -> list[str]:
59
+ """Return a sequence of attribute strings parsed from `attrs`.
60
+
61
+ Each attribute string is stripped of whitespace on both ends.
62
+ """
63
+ attrs = attrs.strip()
64
+ attr_lst = attrs.split()
65
+ return sorted(attr_lst)
66
+
67
+ def _eq_elm_strs(self, line: str, line_2: str):
68
+ """Return True if the element in `line_2` is XML equivalent to the element in
69
+ `line`."""
70
+ front, attrs, close, text = self._parse_line(line)
71
+ front_2, attrs_2, close_2, text_2 = self._parse_line(line_2)
72
+ if front != front_2:
73
+ return False
74
+ if self._attr_seq(attrs) != self._attr_seq(attrs_2):
75
+ return False
76
+ if close != close_2:
77
+ return False
78
+ return text == text_2
79
+
80
+ @classmethod
81
+ def _parse_line(cls, line: str) -> tuple[str, str, str, str]:
82
+ """(front, attrs, close, text) 4-tuple result of parsing XML element `line`."""
83
+ match = cls._xml_elm_line_patt.match(line)
84
+ if match is None:
85
+ return "", "", "", ""
86
+ front, attrs, close, text = [match.group(n) for n in range(1, 5)]
87
+ return front, attrs, close, text
88
+
89
+
90
+ _T = TypeVar("_T")
91
+
92
+
93
+ class MetaOxmlElement(type):
94
+ """Metaclass for BaseOxmlElement."""
95
+
96
+ def __init__(cls, clsname: str, bases: tuple[type, ...], namespace: dict[str, Any]):
97
+ dispatchable = (
98
+ OneAndOnlyOne,
99
+ OneOrMore,
100
+ OptionalAttribute,
101
+ RequiredAttribute,
102
+ ZeroOrMore,
103
+ ZeroOrOne,
104
+ ZeroOrOneChoice,
105
+ )
106
+ for key, value in namespace.items():
107
+ if isinstance(value, dispatchable):
108
+ value.populate_class_members(cls, key)
109
+
110
+
111
+ class BaseAttribute:
112
+ """Base class for OptionalAttribute and RequiredAttribute.
113
+
114
+ Provides common methods.
115
+ """
116
+
117
+ def __init__(self, attr_name: str, simple_type: Type[BaseXmlEnum] | Type[BaseSimpleType]):
118
+ super(BaseAttribute, self).__init__()
119
+ self._attr_name = attr_name
120
+ self._simple_type = simple_type
121
+
122
+ def populate_class_members(self, element_cls: MetaOxmlElement, prop_name: str) -> None:
123
+ """Add the appropriate methods to `element_cls`."""
124
+ self._element_cls = element_cls
125
+ self._prop_name = prop_name
126
+
127
+ self._add_attr_property()
128
+
129
+ def _add_attr_property(self):
130
+ """Add a read/write `.{prop_name}` property to the element class.
131
+
132
+ The property returns the interpreted value of this attribute on access and
133
+ changes the attribute value to its ST_* counterpart on assignment.
134
+ """
135
+ property_ = property(self._getter, self._setter, None)
136
+ # -- assign unconditionally to overwrite element name definition --
137
+ setattr(self._element_cls, self._prop_name, property_)
138
+
139
+ @property
140
+ def _clark_name(self):
141
+ if ":" in self._attr_name:
142
+ return qn(self._attr_name)
143
+ return self._attr_name
144
+
145
+ @property
146
+ def _getter(self) -> Callable[[BaseOxmlElement], Any | None]: ...
147
+
148
+ @property
149
+ def _setter(
150
+ self,
151
+ ) -> Callable[[BaseOxmlElement, Any | None], None]: ...
152
+
153
+
154
+ class 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
212
+ obj.set(self._clark_name, str_value)
213
+
214
+ return set_attr_value
215
+
216
+
217
+ class RequiredAttribute(BaseAttribute):
218
+ """Defines a required attribute on a custom element class.
219
+
220
+ A required attribute is assumed to be present for reading, so does not have a
221
+ default value; its actual value is always used. If missing on read, an
222
+ |InvalidXmlError| is raised. It also does not remove the attribute if |None| is
223
+ assigned. Assigning |None| raises |TypeError| or |ValueError|, depending on the
224
+ simple type of the attribute.
225
+ """
226
+
227
+ @property
228
+ def _docstring(self):
229
+ """Return the string to use as the ``__doc__`` attribute of the property for
230
+ this attribute."""
231
+ return "%s type-converted value of ``%s`` attribute." % (
232
+ self._simple_type.__name__,
233
+ self._attr_name,
234
+ )
235
+
236
+ @property
237
+ def _getter(self) -> Callable[[BaseOxmlElement], Any]:
238
+ """function object suitable for "get" side of attr property descriptor."""
239
+
240
+ def get_attr_value(obj: BaseOxmlElement) -> Any | None:
241
+ attr_str_value = obj.get(self._clark_name)
242
+ if attr_str_value is None:
243
+ raise InvalidXmlError(
244
+ "required '%s' attribute not present on element %s" % (self._attr_name, obj.tag)
245
+ )
246
+ return self._simple_type.from_xml(attr_str_value)
247
+
248
+ get_attr_value.__doc__ = self._docstring
249
+ return get_attr_value
250
+
251
+ @property
252
+ def _setter(self) -> Callable[[BaseOxmlElement, Any], None]:
253
+ """function object suitable for "set" side of attribute property descriptor."""
254
+
255
+ def set_attr_value(obj: BaseOxmlElement, value: Any):
256
+ str_value = self._simple_type.to_xml(value)
257
+ if str_value is None:
258
+ raise ValueError(f"cannot assign {value} to this required attribute")
259
+ obj.set(self._clark_name, str_value)
260
+
261
+ return set_attr_value
262
+
263
+
264
+ class _BaseChildElement:
265
+ """Base class for the child-element classes.
266
+
267
+ The child-element sub-classes correspond to varying cardinalities, such as ZeroOrOne
268
+ and ZeroOrMore.
269
+ """
270
+
271
+ def __init__(self, nsptagname: str, successors: tuple[str, ...] = ()):
272
+ super(_BaseChildElement, self).__init__()
273
+ self._nsptagname = nsptagname
274
+ self._successors = successors
275
+
276
+ def populate_class_members(self, element_cls: MetaOxmlElement, prop_name: str) -> None:
277
+ """Baseline behavior for adding the appropriate methods to `element_cls`."""
278
+ self._element_cls = element_cls
279
+ self._prop_name = prop_name
280
+
281
+ def _add_adder(self):
282
+ """Add an ``_add_x()`` method to the element class for this child element."""
283
+
284
+ def _add_child(obj: BaseOxmlElement, **attrs: Any):
285
+ new_method = getattr(obj, self._new_method_name)
286
+ child = new_method()
287
+ for key, value in attrs.items():
288
+ setattr(child, key, value)
289
+ insert_method = getattr(obj, self._insert_method_name)
290
+ insert_method(child)
291
+ return child
292
+
293
+ _add_child.__doc__ = (
294
+ "Add a new ``<%s>`` child element unconditionally, inserted in t"
295
+ "he correct sequence." % self._nsptagname
296
+ )
297
+ self._add_to_class(self._add_method_name, _add_child)
298
+
299
+ def _add_creator(self):
300
+ """Add a ``_new_{prop_name}()`` method to the element class that creates a new,
301
+ empty element of the correct type, having no attributes."""
302
+ creator = self._creator
303
+ creator.__doc__ = (
304
+ 'Return a "loose", newly created ``<%s>`` element having no attri'
305
+ "butes, text, or children." % self._nsptagname
306
+ )
307
+ self._add_to_class(self._new_method_name, creator)
308
+
309
+ def _add_getter(self):
310
+ """Add a read-only ``{prop_name}`` property to the element class for this child
311
+ element."""
312
+ property_ = property(self._getter, None, None)
313
+ # -- assign unconditionally to overwrite element name definition --
314
+ setattr(self._element_cls, self._prop_name, property_)
315
+
316
+ def _add_inserter(self):
317
+ """Add an ``_insert_x()`` method to the element class for this child element."""
318
+
319
+ def _insert_child(obj: BaseOxmlElement, child: BaseOxmlElement):
320
+ obj.insert_element_before(child, *self._successors)
321
+ return child
322
+
323
+ _insert_child.__doc__ = (
324
+ "Return the passed ``<%s>`` element after inserting it as a chil"
325
+ "d in the correct sequence." % self._nsptagname
326
+ )
327
+ self._add_to_class(self._insert_method_name, _insert_child)
328
+
329
+ def _add_list_getter(self):
330
+ """Add a read-only ``{prop_name}_lst`` property to the element class to retrieve
331
+ a list of child elements matching this type."""
332
+ prop_name = "%s_lst" % self._prop_name
333
+ property_ = property(self._list_getter, None, None)
334
+ setattr(self._element_cls, prop_name, property_)
335
+
336
+ @lazyproperty
337
+ def _add_method_name(self):
338
+ return "_add_%s" % self._prop_name
339
+
340
+ def _add_public_adder(self):
341
+ """Add a public ``add_x()`` method to the parent element class."""
342
+
343
+ def add_child(obj: BaseOxmlElement):
344
+ private_add_method = getattr(obj, self._add_method_name)
345
+ child = private_add_method()
346
+ return child
347
+
348
+ add_child.__doc__ = (
349
+ "Add a new ``<%s>`` child element unconditionally, inserted in t"
350
+ "he correct sequence." % self._nsptagname
351
+ )
352
+ self._add_to_class(self._public_add_method_name, add_child)
353
+
354
+ def _add_to_class(self, name: str, method: Callable[..., Any]):
355
+ """Add `method` to the target class as `name`, unless `name` is already defined
356
+ on the class."""
357
+ if hasattr(self._element_cls, name):
358
+ return
359
+ setattr(self._element_cls, name, method)
360
+
361
+ @property
362
+ def _creator(self) -> Callable[[BaseOxmlElement], BaseOxmlElement]:
363
+ """Callable that creates an empty element of the right type, with no attrs."""
364
+ from docx.oxml.parser import OxmlElement
365
+
366
+ def new_child_element(obj: BaseOxmlElement):
367
+ return OxmlElement(self._nsptagname)
368
+
369
+ return new_child_element
370
+
371
+ @property
372
+ def _getter(self):
373
+ """Return a function object suitable for the "get" side of the property
374
+ descriptor.
375
+
376
+ This default getter returns the child element with matching tag name or |None|
377
+ if not present.
378
+ """
379
+
380
+ def get_child_element(obj: BaseOxmlElement):
381
+ return obj.find(qn(self._nsptagname))
382
+
383
+ get_child_element.__doc__ = (
384
+ "``<%s>`` child element or |None| if not present." % self._nsptagname
385
+ )
386
+ return get_child_element
387
+
388
+ @lazyproperty
389
+ def _insert_method_name(self):
390
+ return "_insert_%s" % self._prop_name
391
+
392
+ @property
393
+ def _list_getter(self):
394
+ """Return a function object suitable for the "get" side of a list property
395
+ descriptor."""
396
+
397
+ def get_child_element_list(obj: BaseOxmlElement):
398
+ return obj.findall(qn(self._nsptagname))
399
+
400
+ get_child_element_list.__doc__ = (
401
+ "A list containing each of the ``<%s>`` child elements, in the o"
402
+ "rder they appear." % self._nsptagname
403
+ )
404
+ return get_child_element_list
405
+
406
+ @lazyproperty
407
+ def _public_add_method_name(self):
408
+ """add_childElement() is public API for a repeating element, allowing new
409
+ elements to be added to the sequence.
410
+
411
+ May be overridden to provide a friendlier API to clients having domain
412
+ appropriate parameter names for required attributes.
413
+ """
414
+ return "add_%s" % self._prop_name
415
+
416
+ @lazyproperty
417
+ def _remove_method_name(self):
418
+ return "_remove_%s" % self._prop_name
419
+
420
+ @lazyproperty
421
+ def _new_method_name(self):
422
+ return "_new_%s" % self._prop_name
423
+
424
+
425
+ class Choice(_BaseChildElement):
426
+ """Defines a child element belonging to a group, only one of which may appear as a child."""
427
+
428
+ @property
429
+ def nsptagname(self):
430
+ return self._nsptagname
431
+
432
+ def populate_class_members( # pyright: ignore[reportIncompatibleMethodOverride]
433
+ self,
434
+ element_cls: MetaOxmlElement,
435
+ group_prop_name: str,
436
+ successors: tuple[str, ...],
437
+ ) -> None:
438
+ """Add the appropriate methods to `element_cls`."""
439
+ self._element_cls = element_cls
440
+ self._group_prop_name = group_prop_name
441
+ self._successors = successors
442
+
443
+ self._add_getter()
444
+ self._add_creator()
445
+ self._add_inserter()
446
+ self._add_adder()
447
+ self._add_get_or_change_to_method()
448
+
449
+ def _add_get_or_change_to_method(self):
450
+ """Add a ``get_or_change_to_x()`` method to the element class for this child
451
+ element."""
452
+
453
+ def get_or_change_to_child(obj: BaseOxmlElement):
454
+ child = getattr(obj, self._prop_name)
455
+ if child is not None:
456
+ return child
457
+ remove_group_method = getattr(obj, self._remove_group_method_name)
458
+ remove_group_method()
459
+ add_method = getattr(obj, self._add_method_name)
460
+ child = add_method()
461
+ return child
462
+
463
+ get_or_change_to_child.__doc__ = (
464
+ "Return the ``<%s>`` child, replacing any other group element if found."
465
+ ) % self._nsptagname
466
+ self._add_to_class(self._get_or_change_to_method_name, get_or_change_to_child)
467
+
468
+ @property
469
+ def _prop_name(self):
470
+ """Property name computed from tag name, e.g. a:schemeClr -> schemeClr."""
471
+ start = self._nsptagname.index(":") + 1 if ":" in self._nsptagname else 0
472
+ return self._nsptagname[start:]
473
+
474
+ @lazyproperty
475
+ def _get_or_change_to_method_name(self):
476
+ return "get_or_change_to_%s" % self._prop_name
477
+
478
+ @lazyproperty
479
+ def _remove_group_method_name(self):
480
+ return "_remove_%s" % self._group_prop_name
481
+
482
+
483
+ class OneAndOnlyOne(_BaseChildElement):
484
+ """Defines a required child element for MetaOxmlElement."""
485
+
486
+ def __init__(self, nsptagname: str):
487
+ super(OneAndOnlyOne, self).__init__(nsptagname, ())
488
+
489
+ def populate_class_members(self, element_cls: MetaOxmlElement, prop_name: str) -> None:
490
+ """Add the appropriate methods to `element_cls`."""
491
+ super(OneAndOnlyOne, self).populate_class_members(element_cls, prop_name)
492
+ self._add_getter()
493
+
494
+ @property
495
+ def _getter(self):
496
+ """Return a function object suitable for the "get" side of the property
497
+ descriptor."""
498
+
499
+ def get_child_element(obj: BaseOxmlElement):
500
+ child = obj.find(qn(self._nsptagname))
501
+ if child is None:
502
+ raise InvalidXmlError(
503
+ "required ``<%s>`` child element not present" % self._nsptagname
504
+ )
505
+ return child
506
+
507
+ get_child_element.__doc__ = "Required ``<%s>`` child element." % self._nsptagname
508
+ return get_child_element
509
+
510
+
511
+ class OneOrMore(_BaseChildElement):
512
+ """Defines a repeating child element for MetaOxmlElement that must appear at least
513
+ once."""
514
+
515
+ def populate_class_members(self, element_cls: MetaOxmlElement, prop_name: str) -> None:
516
+ """Add the appropriate methods to `element_cls`."""
517
+ super(OneOrMore, self).populate_class_members(element_cls, prop_name)
518
+ self._add_list_getter()
519
+ self._add_creator()
520
+ self._add_inserter()
521
+ self._add_adder()
522
+ self._add_public_adder()
523
+ delattr(element_cls, prop_name)
524
+
525
+
526
+ class ZeroOrMore(_BaseChildElement):
527
+ """Defines an optional repeating child element for MetaOxmlElement."""
528
+
529
+ def populate_class_members(self, element_cls: MetaOxmlElement, prop_name: str) -> None:
530
+ """Add the appropriate methods to `element_cls`."""
531
+ super(ZeroOrMore, self).populate_class_members(element_cls, prop_name)
532
+ self._add_list_getter()
533
+ self._add_creator()
534
+ self._add_inserter()
535
+ self._add_adder()
536
+ self._add_public_adder()
537
+ delattr(element_cls, prop_name)
538
+
539
+
540
+ class ZeroOrOne(_BaseChildElement):
541
+ """Defines an optional child element for MetaOxmlElement."""
542
+
543
+ def populate_class_members(self, element_cls: MetaOxmlElement, prop_name: str) -> None:
544
+ """Add the appropriate methods to `element_cls`."""
545
+ super(ZeroOrOne, self).populate_class_members(element_cls, prop_name)
546
+ self._add_getter()
547
+ self._add_creator()
548
+ self._add_inserter()
549
+ self._add_adder()
550
+ self._add_get_or_adder()
551
+ self._add_remover()
552
+
553
+ def _add_get_or_adder(self):
554
+ """Add a ``get_or_add_x()`` method to the element class for this child
555
+ element."""
556
+
557
+ def get_or_add_child(obj: BaseOxmlElement):
558
+ child = getattr(obj, self._prop_name)
559
+ if child is None:
560
+ add_method = getattr(obj, self._add_method_name)
561
+ child = add_method()
562
+ return child
563
+
564
+ get_or_add_child.__doc__ = (
565
+ "Return the ``<%s>`` child element, newly added if not present."
566
+ ) % self._nsptagname
567
+ self._add_to_class(self._get_or_add_method_name, get_or_add_child)
568
+
569
+ def _add_remover(self):
570
+ """Add a ``_remove_x()`` method to the element class for this child element."""
571
+
572
+ def _remove_child(obj: BaseOxmlElement):
573
+ obj.remove_all(self._nsptagname)
574
+
575
+ _remove_child.__doc__ = ("Remove all ``<%s>`` child elements.") % self._nsptagname
576
+ self._add_to_class(self._remove_method_name, _remove_child)
577
+
578
+ @lazyproperty
579
+ def _get_or_add_method_name(self):
580
+ return "get_or_add_%s" % self._prop_name
581
+
582
+
583
+ class ZeroOrOneChoice(_BaseChildElement):
584
+ """Correspondes to an ``EG_*`` element group where at most one of its members may
585
+ appear as a child."""
586
+
587
+ def __init__(self, choices: Sequence[Choice], successors: tuple[str, ...] = ()):
588
+ self._choices = choices
589
+ self._successors = successors
590
+
591
+ def populate_class_members(self, element_cls: MetaOxmlElement, prop_name: str) -> None:
592
+ """Add the appropriate methods to `element_cls`."""
593
+ super(ZeroOrOneChoice, self).populate_class_members(element_cls, prop_name)
594
+ self._add_choice_getter()
595
+ for choice in self._choices:
596
+ choice.populate_class_members(element_cls, self._prop_name, self._successors)
597
+ self._add_group_remover()
598
+
599
+ def _add_choice_getter(self):
600
+ """Add a read-only ``{prop_name}`` property to the element class that returns
601
+ the present member of this group, or |None| if none are present."""
602
+ property_ = property(self._choice_getter, None, None)
603
+ # assign unconditionally to overwrite element name definition
604
+ setattr(self._element_cls, self._prop_name, property_)
605
+
606
+ def _add_group_remover(self):
607
+ """Add a ``_remove_eg_x()`` method to the element class for this choice
608
+ group."""
609
+
610
+ def _remove_choice_group(obj: BaseOxmlElement):
611
+ for tagname in self._member_nsptagnames:
612
+ obj.remove_all(tagname)
613
+
614
+ _remove_choice_group.__doc__ = "Remove the current choice group child element if present."
615
+ self._add_to_class(self._remove_choice_group_method_name, _remove_choice_group)
616
+
617
+ @property
618
+ def _choice_getter(self):
619
+ """Return a function object suitable for the "get" side of the property
620
+ descriptor."""
621
+
622
+ def get_group_member_element(obj: BaseOxmlElement):
623
+ return obj.first_child_found_in(*self._member_nsptagnames)
624
+
625
+ get_group_member_element.__doc__ = (
626
+ "Return the child element belonging to this element group, or "
627
+ "|None| if no member child is present."
628
+ )
629
+ return get_group_member_element
630
+
631
+ @lazyproperty
632
+ def _member_nsptagnames(self):
633
+ """Sequence of namespace-prefixed tagnames, one for each of the member elements
634
+ of this choice group."""
635
+ return [choice.nsptagname for choice in self._choices]
636
+
637
+ @lazyproperty
638
+ def _remove_choice_group_method_name(self):
639
+ return "_remove_%s" % self._prop_name
640
+
641
+
642
+ # -- lxml typing isn't quite right here, just ignore this error on _Element --
643
+ class BaseOxmlElement(etree.ElementBase, metaclass=MetaOxmlElement):
644
+ """Effective base class for all custom element classes.
645
+
646
+ Adds standardized behavior to all classes in one place.
647
+ """
648
+
649
+ def __repr__(self):
650
+ return "<%s '<%s>' at 0x%0x>" % (
651
+ self.__class__.__name__,
652
+ self._nsptag,
653
+ id(self),
654
+ )
655
+
656
+ def first_child_found_in(self, *tagnames: str) -> _Element | None:
657
+ """First child with tag in `tagnames`, or None if not found."""
658
+ for tagname in tagnames:
659
+ child = self.find(qn(tagname))
660
+ if child is not None:
661
+ return child
662
+ return None
663
+
664
+ def insert_element_before(self, elm: ElementBase, *tagnames: str):
665
+ successor = self.first_child_found_in(*tagnames)
666
+ if successor is not None:
667
+ successor.addprevious(elm)
668
+ else:
669
+ self.append(elm)
670
+ return elm
671
+
672
+ def remove_all(self, *tagnames: str) -> None:
673
+ """Remove child elements with tagname (e.g. "a:p") in `tagnames`."""
674
+ for tagname in tagnames:
675
+ matching = self.findall(qn(tagname))
676
+ for child in matching:
677
+ self.remove(child)
678
+
679
+ @property
680
+ def xml(self) -> str:
681
+ """XML string for this element, suitable for testing purposes.
682
+
683
+ Pretty printed for readability and without an XML declaration at the top.
684
+ """
685
+ return serialize_for_reading(self)
686
+
687
+ def xpath(self, xpath_str: str) -> Any: # pyright: ignore[reportIncompatibleMethodOverride]
688
+ """Override of `lxml` _Element.xpath() method.
689
+
690
+ Provides standard Open XML namespace mapping (`nsmap`) in centralized location.
691
+ """
692
+ return super().xpath(xpath_str, namespaces=nsmap)
693
+
694
+ @property
695
+ def _nsptag(self) -> str:
696
+ return NamespacePrefixedTag.from_clark_name(self.tag)