suggestion for os.path.commonprefix

Tim Peters tim_one at email.msn.com
Tue May 21 23:07:21 EDT 2002


[Cristian Barbarosie]
> I noticed the following peculiar behaviour os.path.commonprefix:
>
> >>> os.path.commonprefix(['/home/someuser/modulef/essay.tex',
> ... '/home/someuser/mollifiers/fig01.ps'])
> '/home/someuser/mo'

As the docs say,

    Return the longest path prefix (taken character-by-character) that is
    a prefix of all paths in list.  If list is empty, return the empty
    string ('').  Note that this may return invalid paths because it works
    a character at a time.

>   I think the answer should be '/home/someuser/'. At least, this is
> what I expect when I do pathname manipulations in Python.
>   So I propose the following replacement for os.path.commonprefix:

That was tried before, and it broke too much code.  You could push for a new
function with a new name, but commonprefix won't change again.

If you want to write one, note that os.sep isn't enough:  os.altsep also
needs to be considered, and at least on Windows both forward and backward
slashes are legit path separators but os.altsep is None.  Then some people
will complain that it's platform-dependent (commonprefix as-is is not).
Others will insist that, in your example, you leave the trailing slash in,
while others will insist that you don't.  Have fun <wink>.






More information about the Python-list mailing list