[Python-ideas] os.path.commonprefix: Yes that old chestnut.

Paul Moore p.f.moore at gmail.com
Tue Mar 24 12:56:25 CET 2015


On 23 March 2015 at 21:33, Gregory P. Smith <greg at krypto.org> wrote:
> +1 pathlib would be the appropriate place for the correctly behaving
> function to appear.

OK, so here's a question. What actual use cases exist for a
common_prefix function? The reason I ask is that I'm looking at some
of the edge cases, and the obvious behaviour isn't particularly clear
to me.

For example, common_prefix('a/b/file.c', 'a/b/file.c'). The common
prefix is obviously 'a/b/file.c' - but I can imagine people *actually*
wanting the common *directory* containing both files. But taken
literally, that's only possible if you check the filesystem, so it
would no longer be a PurePath operation.

And what about common_prefix('foo/bar', '../here/foo')? Or
common_prefix('bar/baz', 'foo/../bar/baz')? Pathlib avoids collapsing
.. because the meaning could change in the face of symlinks. I believe
the same applies here. Maybe you need to call resolve() before doing
the common prefix operation (but that gives an absolute path).

With the above limitations, would a common_prefix function actually
help typical use cases? In my experience, doing list operations on
pathobj.parts is often simple enough that I don't need specialised
functions like common_prefix...

Getting the edge cases right is fiddly enough for common_prefix that a
specialised function is a reasonable idea, but only if the "obvious"
behaviour is clear. If there's a lot of conflicting possibilities,
maybe a recipe in the docs would be a better option.

Paul


More information about the Python-ideas mailing list