cleanup
cleanup
¶
Removing the things a document carries that nothing points at.
Three separate kinds of dead weight, each reached the same way — find what is referenced, drop the rest:
- Styles. A document created by this library defines 164 of them and a
one-paragraph document references one. This is Styles.remove_unused, built on
the reachability closure in
docx.styles.usage. - Numbering definitions. A
w:abstractNumnow:numpoints at, and aw:numnow:numPrpoints at, are both dead. - Orphan media. An image part related from nothing, left behind when the run or
shape that displayed it was deleted. The
.delete()API added in 2.0.0 makes this reachable from ordinary use.
cleanup runs the lot; the individual operations stay public, because "remove unused styles but leave my media alone" is a reasonable thing to want.
remove_unused_numbering
¶
remove_unused_numbering(
document_part: DocumentPart,
) -> tuple[Tuple[int, ...], Tuple[int, ...]]
Drop the numbering definitions nothing references; return (numIds, abstractNumIds).
A w:num is dead when no w:numPr in any story part or style names its numId. A
w:abstractNum is dead when no surviving w:num points at it and no surviving
abstract definition chains to it through w:numStyleLink.
Does nothing, and reports nothing removed, for a document with no numbering part — reading one would create it.
Source code in src/docx/cleanup.py
remove_orphan_media
¶
remove_orphan_media(
document_part: DocumentPart,
) -> Tuple[str, ...]
Drop image relationships nothing in the document part's XML refers to.
An r:embed, r:link or r:id naming the relationship is what keeps an image
alive. Deleting a paragraph that held a picture leaves the relationship and the part
behind; this is what removes them.
Only the document part's own image relationships are considered. A picture in a header or a footnote belongs to that part's relationships and is not this pass's business — a header image is not orphaned by anything happening in the body.
Source code in src/docx/cleanup.py
cleanup
¶
cleanup(
document_part: DocumentPart,
*,
styles: bool = True,
numbering: bool = True,
media: bool = True,
latent_styles: bool = False,
keep: tuple[str, ...] = (),
) -> CleanupResult
Remove what this document carries that nothing points at.
Each flag turns one pass on or off; keep names styles to preserve along with their
dependencies, as for Styles.remove_unused.
latent_styles is False by default and separate from styles on purpose:
removing a w:lsdException changes what a user sees in Word's style gallery rather
than how the document renders, which is a different kind of change from removing a
style definition.
Styles are pruned before numbering, so a numbering definition kept alive only by a style that is about to go is correctly seen as dead.