feat: support standard library pathlib.Path for Document open/save#1571
Open
SamYue1 wants to merge 1 commit into
Open
feat: support standard library pathlib.Path for Document open/save#1571SamYue1 wants to merge 1 commit into
SamYue1 wants to merge 1 commit into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
python-docxcurrently only acceptsstrorIO[bytes]for theDocument()factory function andDocument.save(). Passing apathlib.Pathobject — the standard way to represent file paths in modern Python — either causes type-checking errors (e.g. withpyright,mypy) or, in the case ofPhysPkgReader, bypasses the_DirPkgReadercode path becauseisinstance(pkg_file, str)does not matchPathobjects.Solution
str | IO[bytes]tostr | os.PathLike[str] | IO[bytes]across the call chain:Document(),Document.save(),DocumentPart.save(),OpcPackage.open(),OpcPackage.save().os.PathLike→strat each entry point usingos.fspath()so that downstream code (which expectsstr) continues to work unchanged.PhysPkgReader.__new__()to checkisinstance(pkg_file, (str, os.PathLike))instead ofisinstance(pkg_file, str), soPathobjects are correctly routed to_DirPkgReaderor_ZipPkgReader.Changes
src/docx/api.py— type annotation + conversion inDocument()src/docx/document.py— type annotation + conversion inDocument.save()src/docx/parts/document.py— type annotation + conversion inDocumentPart.save()src/docx/opc/package.py— type annotation + conversion inOpcPackage.open()/save()src/docx/opc/phys_pkg.py— fixisinstancecheck inPhysPkgReader.__new__()tests/test_api.py,tests/test_document.py,tests/parts/test_document.py,tests/opc/test_phys_pkg.py— add unit tests forPathsupportBackward Compatibility
Fully backward compatible. All 90+ existing tests pass without modification.