Not commonprefix (was RE: [Python-Dev] commonprefix - the beast just won't die...)

Tim Peters tim_one@email.msn.com
Tue, 22 Aug 2000 22:43:04 -0400


[Skip Montanaro]
> I reverted the changes to {posix,nt,dos}path.commonprefix this morning,
> updated the tests (still to be checked in) and was starting to work on
> documentation changes, when I realized that something Guido
> said about using dirname to trim to the common directory prefix is
> probably not correct.  Here's an example.  The common prefix of
>     ["/usr/local", "/usr/local/bin"]
> is
>     "/usr/local"
> If you blindly apply dirname to that (which is what I think Guido
> suggested as the way to make commonprefix do what I wanted, you wind
> up with
>     "/usr"
> which isn't going to be correct on most Unix flavors.  Instead, you
> need to check that the prefix doesn't exist or isn't a directory
> before applying dirname.

[Thomas Wouters]
> And even that won't work, in a case like this:
>
> /home/swenson/
> /home/swen/
>
> (common prefix would be /home/swen, which is a directory)

Note that Guido's suggestion does work for that, though.

> or cases like this:
>
> /home/swenson/
> /home/swenniker/
>
> where another directory called
> /home/swen
>
> exists.

Ditto.  This isn't coincidence:  Guido's suggestion works as-is *provided
that* each dirname in the original collection ends with a path separator.
Change Skip's example to

    ["/usr/local/", "/usr/local/bin/"]
                ^ stuck in slashes ^

and Guido's suggestion works fine too.  But these are purely
string-crunching functions, and "/usr/local" *screams* "directory" to people
thanks to its specific name.  Let's make the test case absurdly "simple":

    ["/x/y", "/x/y"]

What's the "common (directory) prefix" here?  Well, there's simply no way to
know at this level.  It's /x/y if y is a directory, or /x if y's just a
regular file.  Guido's suggestion returns /x in this case, or /x/y if you
add trailing slashes to both.  If you don't tell a string gimmick which
inputs are and aren't directories, you can't expect it to guess.

I'll say again, if you want a new function, press for one!  Just leave
commonprefix alone.