Hi! I propose a small, backwards compatible improvement to
pathlib, to allow method chaining and therefore cleaner user code. For example, to write a new file in a new directory, I currently use:
from pathlib import Path d = Path().joinpath('new_directory') d.mkdir() d.joinpath('new_file').write_text('text')
This awkward, multi-statement form is required because
Path.mkdir() returns nothing. If we changed
Path.mkdir() to instead return
self, then we could do some cleaner method chaining:
from pathlib import Path Path().joinpath('new_directory').mkdir().joinpath('new_file').write_text('text')
I may be missing something here, but here are some of the things I thought of:
- Backwards compatible. Users shouldn’t currently be using the return value of
mkdir(), since currently it is always
- Allows simpler user code.
- Semantically OK: As an analogy,
list.reverse()returns nothing, because it modifies the input in-place. This is a good API, because it prevents users from doing the mistake of
new_list = old_list.reverse().
mkdir()also modifies the underlying state (of the filesystem), but unlike
mkdir()is very obvious that it does that, and it just returns the original path, instead of a modified instance. Is there some semantic problem with returning
mkdir()that I don’t see?
- Not pre-emptive. As soon as we add a return value, then it’s locked in and we can’t change it, else we break users. However, this choice of return value is the only sane choice I can see. I can’t see how in the future we will regret this choice and wish we had returned something else. We already can tell success vs failure based on exceptions. Is there a different candidate return value that I’ve overlooked?
I looked through the rest of
pathlib, and here are some other candidates for this same tweak:
Path.touch(): Similar to
mkdir(). I would vote for changing this as well to return
Path.link_to(): A bit weird, should this return src or dst? Probably leave this as is.
Path.rmdir(): Could return the parent directory? Probably should leave this as is.
Path.chmod(): This is a bit unrelated, but this could return the old mode and permissions? Probably should leave this as is.
- Something else?
I can submit a PR for this if reception here is positive. Thanks for your thoughts!
PS: Background, further reading: Issue 31163: Return destination path in Path.rename and Path.replace - Python tracker