usage
usage
¶
Which styles a document actually uses.
The interesting part is getting "used" right. A naive scan of w:pStyle in
word/document.xml gets the wrong answer in several ways, and each of them is a real
document:
- Every story part, not just the body. Headers, footers, footnotes, endnotes and comments are separate parts with their own content and their own style references.
- Indirect references. A style can be reachable without ever being applied — as the
w:basedOnof a used style, as itsw:next, as itsw:link, from a numbering level'sw:pStyle, or from thew:tblStylePrconditional formatting inside a table style. - The default styles. The style carrying
w:default="1"applies to every paragraph with now:pStyleat all. It is used by definition and has zero direct references.
So "used" is a reachability closure, not a membership test: seed from the direct applications, then follow the reference edges until the set stops growing.
The closure runs on style ids, which is what the XML references;
docx.styles.styles.Styles keys on names, which is what the API exposes, and
BabelFish translates the built-ins between the two spellings. Mixing the two is a
recurring source of bugs, so the translation happens only at the boundary.
StyleUsage
¶
Bases: NamedTuple
A report of which styles a document defines and which of them it uses.
Iterating yields the style ids in use. str() gives the one-paragraph summary
that print shows.
compute_usage
¶
compute_usage(
styles_elm: CT_Styles,
document_part: DocumentPart | None,
keep: Iterable[str] = (),
*,
seed_defaults: bool = True,
) -> StyleUsage
The style-usage report for styles_elm as used by document_part.
keep names extra style ids to treat as used along with their own closure — for a
caller who plans to apply a style that nothing references yet.
seed_defaults puts the w:default="1" styles into the closure whether or not
anything references them, which is the truthful reading: they apply to content that
names no style at all. Passing False answers the narrower question of what is
reachable by reference alone, which is what a caller deliberately pruning the
defaults needs.
With no document_part there is no content to scan, so only the defaults and keep
seed the closure. That is the honest answer for a styles part reached on its own
rather than a claim that nothing is used.
Source code in src/docx/styles/usage.py
latent_exception_names
¶
latent_exception_names(
styles_elm: CT_Styles,
) -> Tuple[str, ...]
Every w:lsdException/@w:name in the latent-styles block, defined or not.
is_default_style
¶
True when style is the w:default="1" style of its type.