bpo-24132: Direct sub-classing of pathlib.Path by kfollstad · Pull Request #26438 · python/cpython (original) (raw)

Updated based on feedback - currently marked as draft

I submit for your consideration what I believe is the first working version (with documentation) of an extensible, subclassable PurePath/Path to close bpo-24132, a 6-year-old bug. I have also posted a more detailed version of this explanation on discuss.python.org because this fix involves adding classes to pathlib and understanding why that is required takes a significant explanation.

These classes are a complete set of alternatives to PurePath and Path which omit the factory design but instead attach the flavour to the class at the time of instantiation. These newly designed classes still pass all of the test cases that are run against PurePath and Path on both Windows and Linux. Because they omit the factory design, they don't have inverted dependencies and therefore are naively subclassable and extensible in any way you see fit.

To this end I give you:

SimplePath (subclassable alternative to PurePath)
SimplePosixPath (subclassable alternative to PurePosixPath)
SimpleWindowsPath (subclassable alternative to PureWindowsPath)
FilePath (subclassable alternative to Path/PosixPath/WindowsPath)

On Windows, SimplePath behaves as if it were PureWindowsPath. On Posix, it behaves as PurePosixPath. Similarly, FilePath behaves like WindowsPath on Windows and PosixPath on Posix. These four classes combined could, if one were so inclined, act as a complete replacement for the existing six Path/PurePath classes.

Despite being 11 commits, it's essentially just two refactors. The first splits the two responsibilities PurePath has, separating the base class methods into _PurePathBase. The second does the same with Path, moving the base class methods into PathIOMixin. The other commits are just minor tweaks and documentation to account for all of that.

https://bugs.python.org/issue24132