Skip to content

feat: support standard library pathlib.Path for Document open/save#1571

Open
SamYue1 wants to merge 1 commit into
python-openxml:masterfrom
SamYue1:feat/pathlib-path-support
Open

feat: support standard library pathlib.Path for Document open/save#1571
SamYue1 wants to merge 1 commit into
python-openxml:masterfrom
SamYue1:feat/pathlib-path-support

Conversation

@SamYue1

@SamYue1 SamYue1 commented Jul 25, 2026

Copy link
Copy Markdown

Problem

python-docx currently only accepts str or IO[bytes] for the Document() factory function and Document.save(). Passing a pathlib.Path object — the standard way to represent file paths in modern Python — either causes type-checking errors (e.g. with pyright, mypy) or, in the case of PhysPkgReader, bypasses the _DirPkgReader code path because isinstance(pkg_file, str) does not match Path objects.

Solution

  • Update type annotations from str | IO[bytes] to str | os.PathLike[str] | IO[bytes] across the call chain: Document(), Document.save(), DocumentPart.save(), OpcPackage.open(), OpcPackage.save().
  • Convert os.PathLikestr at each entry point using os.fspath() so that downstream code (which expects str) continues to work unchanged.
  • Fix PhysPkgReader.__new__() to check isinstance(pkg_file, (str, os.PathLike)) instead of isinstance(pkg_file, str), so Path objects are correctly routed to _DirPkgReader or _ZipPkgReader.

Changes

  • src/docx/api.py — type annotation + conversion in Document()
  • src/docx/document.py — type annotation + conversion in Document.save()
  • src/docx/parts/document.py — type annotation + conversion in DocumentPart.save()
  • src/docx/opc/package.py — type annotation + conversion in OpcPackage.open() / save()
  • src/docx/opc/phys_pkg.py — fix isinstance check in PhysPkgReader.__new__()
  • tests/test_api.py, tests/test_document.py, tests/parts/test_document.py, tests/opc/test_phys_pkg.py — add unit tests for Path support

Backward Compatibility

Fully backward compatible. All 90+ existing tests pass without modification.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant