Make pathlib extensible

Here’s a table showing the proposed methods of the pathlib.abc classes (from the previous post):

JoinablePath ReadablePath WritablePath
Abstract methods __str__()
with_segments()
parser
__open_rb__()
iterdir()
readlink()
info
__open_wb__()
mkdir()
symlink_to()
Non-abstract methods __truediv__()
__rtruediv__()
joinpath()
anchor
parts
parent
parents
name
suffix
suffixes
stem
with_name()
with_stem()
with_suffix()
match()
full_match()
read_bytes()
read_text()
exists()
is_dir()
is_file()
is_symlink()
glob()
rglob()
walk()
copy()
copy_into()
write_bytes()
write_text()

Feedback welcome

3 Likes

Here’s a way to replace the double-duty ReadablePath.open() method without resorting to dunder methods: add a stream argument to ReadablePath.read_bytes() and WritablePath.write_bytes(). When stream=True, these methods would return a readable or writable file object in binary mode. In the ABCs they’d be abstract. There’s analogous behaviour in libraries like requests, and it might appeal to users who feel daunted by the values accepted by open(mode=...).

1 Like

What about instead of adding the openable protocol, or the stream mode, provide a decorator in pathlib, that takes a function of type Callable[[JoinablePath], IO[bytes]] and returns a valid ReadablePath.open(...) or WritablePath.open(...) method.

Which basically provides the same support for users implementing new pathlib subclasses without the new __open_rb__, __open_wb__ dunders.

Please could you sketch some code? I don’t quite follow.