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

Paul Moore p.f.moore at gmail.com
Mon Mar 23 23:48:47 CET 2015


On 23 March 2015 at 22:09, Antoine Pitrou <solipsis at pitrou.net> wrote:
> On Mon, 23 Mar 2015 21:33:48 +0000
> "Gregory P. Smith" <greg at krypto.org> wrote:
>> +1 pathlib would be the appropriate place for the correctly behaving
>> function to appear.
>
> Patches welcome :-)

I'll see what I can do. Basically it's just

def commonprefix(p1, p2):
    cp = []
    for (pp1, pp2) in zip(p1.parts, p2.parts):
        if pp1 != pp2:
            break
        cp.append(pp1)
    return pathlib.Path(*cp)

(extended to an arbitrary number of args) but getting the corner cases
right is a little more tricky. If there is no common prefix, I guess
returning None is correct - it's the nearest equivalent to
os.path.commonprefix returning ''. The type of the return value should
be a concrete type - probably type(p1)?

Maybe this should be a method on Path objects - p.commonprefix(p1, p2,
...) although it seems a bit odd that the first argument (self) is
treated differently in the signature.

Anyone got any preferences?
Paul


More information about the Python-ideas mailing list