How to go on with a tiny improvement idea for pathlib?

Hi, I’m new to this forum, so I don’t want to spam the ideas discussion right from the start (seeing the complex discussions taking place there).

What’s the best way to pursue this small idea for extending the functionality of pathlib?

Currently there is pathlib.relative_to() which returns the relative path between to Path objects, but it’s limited to cases where one path is a direct subpath of the other.

In some use cases we need a relative path, even if there is no direct way, so we need “up-steps” in the form of ../ elements in the path. With this addition, all relations between paths on one file system can be shown as a relative path.

Example:
/foo/bar/baz relative to /foo/bar/abc/xyz is ../../baz.

I’ve written a small function to return this kind of relative path if pathlib.relative_to() doesn’t work:

def path_relative_to_ext(path: Path, relative_to: Path):
    """Return the relative path to another path, using upward steps ('../') if path is not a subpath of relative_to."""
    try:
        return path.relative_to(relative_to)
    except ValueError:
        for upsteps, basepath in enumerate(relative_to.parents, start=1):
            try:
                relpath = path.relative_to(basepath)
                return Path('../' * upsteps).joinpath(relpath)
            except ValueError:
                pass
        raise ValueError(f"Cannot determine a relative path from '{str(path)}' to '{str(relative_to)}'.")

This works for me, but I was thinking the resulting code might be nicer if this functionality was part of pathlib. I would suggest to implement it as an option flag (can’t come up with a good name though) for pathlib.relative_to().
This would not break any code relying on the existing API and it would not introduce another method but still extend the possible use cases of the existing library.

Of course there might be cases I haven’t thought about which might make things more complicated than I appreciated.
And I assume there are more efficient ways to implement this from inside pathlib - the above code is just meant as a proof of concept.

Hey, so there’s already an open issue and a corresponding PR to add this functionality; looks like the main blockers are just a docs update, bikeshedding over the parameter name and fixing merge conflicts, plus a core dev reviewing and commiting it. If that continues to stall out, you could propose a new PR based on that one with any enhancements from this one and the requested changes, but for now I’d advise not duplicating effort. Thanks!