Skip to content

package

package

Objects that implement reading and writing OPC packages.

OpcPackage

Main API class for |python-opc|.

A new instance is constructed by calling the open class method with a path to a package file or file-like object containing one.

core_properties property

core_properties: CoreProperties

CoreProperties object providing read/write access to the Dublin Core properties for this document.

custom_properties property

custom_properties: CustomProperties

CustomProperties object providing read/write access to the arbitrary named values attached to this document.

extended_properties property

extended_properties: ExtendedProperties

ExtendedProperties object providing read/write access to the application-specific properties for this document.

main_document_part property

main_document_part

Return a reference to the main document part for this package.

Examples include a document part for a WordprocessingML package, a presentation part for a PresentationML package, or a workbook part for a SpreadsheetML package.

parts property

parts: list[Part]

Return a list containing a reference to each of the parts in this package.

after_unmarshal

after_unmarshal()

Entry point for any post-unmarshaling processing.

May be overridden by subclasses without forwarding call to super.

Source code in src/docx/opc/package.py
def after_unmarshal(self):
    """Entry point for any post-unmarshaling processing.

    May be overridden by subclasses without forwarding call to super.
    """
    # don't place any code here, just catch call if not overridden by
    # subclass
    pass

iter_rels

iter_rels() -> Iterator[_Relationship]

Generate exactly one reference to each relationship in the package by performing a depth-first traversal of the rels graph.

Source code in src/docx/opc/package.py
def iter_rels(self) -> Iterator[_Relationship]:
    """Generate exactly one reference to each relationship in the package by
    performing a depth-first traversal of the rels graph."""

    def walk_rels(
        source: OpcPackage | Part, visited: list[Part] | None = None
    ) -> Iterator[_Relationship]:
        visited = [] if visited is None else visited
        for rel in source.rels.values():
            yield rel
            if rel.is_external:
                continue
            part = rel.target_part
            if part in visited:
                continue
            visited.append(part)
            new_source = part
            for rel in walk_rels(new_source, visited):
                yield rel

    for rel in walk_rels(self):
        yield rel

iter_parts

iter_parts() -> Iterator[Part]

Generate exactly one reference to each of the parts in the package by performing a depth-first traversal of the rels graph.

Source code in src/docx/opc/package.py
def iter_parts(self) -> Iterator[Part]:
    """Generate exactly one reference to each of the parts in the package by
    performing a depth-first traversal of the rels graph."""

    def walk_parts(source, visited=[]):
        for rel in source.rels.values():
            if rel.is_external:
                continue
            part = rel.target_part
            if part in visited:
                continue
            visited.append(part)
            yield part
            new_source = part
            for part in walk_parts(new_source, visited):
                yield part

    for part in walk_parts(self):
        yield part

load_rel

load_rel(
    reltype: str,
    target: Part | str,
    rId: str,
    is_external: bool = False,
)

Return newly added _Relationship instance of reltype between this part and target with key rId.

Target mode is set to RTM.EXTERNAL if is_external is True. Intended for use during load from a serialized package, where the rId is well known. Other methods exist for adding a new relationship to the package during processing.

Source code in src/docx/opc/package.py
def load_rel(self, reltype: str, target: Part | str, rId: str, is_external: bool = False):
    """Return newly added |_Relationship| instance of `reltype` between this part
    and `target` with key `rId`.

    Target mode is set to ``RTM.EXTERNAL`` if `is_external` is |True|. Intended for
    use during load from a serialized package, where the rId is well known. Other
    methods exist for adding a new relationship to the package during processing.
    """
    return self.rels.add_relationship(reltype, target, rId, is_external)

next_partname

next_partname(template: str) -> PackURI

Return a PackURI instance representing partname matching template.

The returned part-name has the next available numeric suffix to distinguish it from other parts of its type. template is a printf (%)-style template string containing a single replacement item, a '%d' to be used to insert the integer portion of the partname. Example: "/word/header%d.xml"

Source code in src/docx/opc/package.py
def next_partname(self, template: str) -> PackURI:
    """Return a |PackURI| instance representing partname matching `template`.

    The returned part-name has the next available numeric suffix to distinguish it
    from other parts of its type. `template` is a printf (%)-style template string
    containing a single replacement item, a '%d' to be used to insert the integer
    portion of the partname. Example: "/word/header%d.xml"
    """
    partnames = {part.partname for part in self.iter_parts()}
    for n in range(1, len(partnames) + 2):
        candidate_partname = template % n
        if candidate_partname not in partnames:
            return PackURI(candidate_partname)

open classmethod

open(pkg_file: str | PathLike[str] | IO[bytes]) -> Self

Return an OpcPackage instance loaded with the contents of pkg_file.

Source code in src/docx/opc/package.py
@classmethod
def open(cls, pkg_file: str | os.PathLike[str] | IO[bytes]) -> Self:
    """Return an |OpcPackage| instance loaded with the contents of `pkg_file`."""
    if isinstance(pkg_file, os.PathLike):
        pkg_file = os.fspath(pkg_file)
    pkg_reader = PackageReader.from_file(pkg_file)
    package = cls()
    Unmarshaller.unmarshal(pkg_reader, package, PartFactory)
    return package
part_related_by(reltype: str) -> Part

Return part to which this package has a relationship of reltype.

Raises KeyError if no such relationship is found and ValueError if more than one such relationship is found.

Source code in src/docx/opc/package.py
def part_related_by(self, reltype: str) -> Part:
    """Return part to which this package has a relationship of `reltype`.

    Raises |KeyError| if no such relationship is found and |ValueError| if more than
    one such relationship is found.
    """
    return self.rels.part_with_reltype(reltype)

relate_to

relate_to(part: Part, reltype: str)

Return rId key of new or existing relationship to part.

If a relationship of reltype to part already exists, its rId is returned. Otherwise a new relationship is created and that rId is returned.

Source code in src/docx/opc/package.py
def relate_to(self, part: Part, reltype: str):
    """Return rId key of new or existing relationship to `part`.

    If a relationship of `reltype` to `part` already exists, its rId is returned. Otherwise a
    new relationship is created and that rId is returned.
    """
    rel = self.rels.get_or_add(reltype, part)
    return rel.rId

rels

rels()

Return a reference to the Relationships instance holding the collection of relationships for this package.

Source code in src/docx/opc/package.py
@lazyproperty
def rels(self):
    """Return a reference to the |Relationships| instance holding the collection of
    relationships for this package."""
    return Relationships(PACKAGE_URI.baseURI)

save

save(pkg_file: str | PathLike[str] | IO[bytes])

Save this package to pkg_file.

pkg_file can be either a file-path or a file-like object.

Source code in src/docx/opc/package.py
def save(self, pkg_file: str | os.PathLike[str] | IO[bytes]):
    """Save this package to `pkg_file`.

    `pkg_file` can be either a file-path or a file-like object.
    """
    if isinstance(pkg_file, os.PathLike):
        pkg_file = os.fspath(pkg_file)
    for part in self.parts:
        part.before_marshal()
    PackageWriter.write(pkg_file, self.rels, self.parts)

Unmarshaller

Hosts static methods for unmarshalling a package from a PackageReader.

unmarshal staticmethod

unmarshal(pkg_reader, package, part_factory)

Construct graph of parts and realized relationships based on the contents of pkg_reader, delegating construction of each part to part_factory.

Package relationships are added to pkg.

Source code in src/docx/opc/package.py
@staticmethod
def unmarshal(pkg_reader, package, part_factory):
    """Construct graph of parts and realized relationships based on the contents of
    `pkg_reader`, delegating construction of each part to `part_factory`.

    Package relationships are added to `pkg`.
    """
    parts = Unmarshaller._unmarshal_parts(pkg_reader, package, part_factory)
    Unmarshaller._unmarshal_relationships(pkg_reader, package, parts)
    for part in parts.values():
        part.after_unmarshal()
    package.after_unmarshal()